温馨提示×

ubuntu php怎样做伪静态

小樊
35
2026-10-10 07:01:02
栏目: 编程语言

在 Ubuntu 下让 PHP 项目支持伪静态(URL Rewrite),通常取决于你使用的 Web 服务器。最常见的是 Apache 和 Nginx。下面分别说明。


一、Apache + Ubuntu + PHP(最常见)

1. 开启 rewrite 模块

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 修改 Apache 配置(允许 .htaccess)

编辑站点配置:

sudo nano /etc/apache2/sites-available/000-default.conf

在 <VirtualHost *:80> 里加上:

<Directory /var/www/html>
    AllowOverride All
</Directory>

然后重启:

sudo systemctl restart apache2

3. 在项目根目录创建 .htaccess

示例(把所有请求转发到 index.php):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

✅ 这样 example.com/article/1 就会交给 index.php 处理。


二、Nginx + Ubuntu + PHP(推荐高性能)

1. 修改 Nginx 站点配置

sudo nano /etc/nginx/sites-available/default

示例配置:

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    }
}

2. 测试并重启

sudo nginx -t
sudo systemctl restart nginx

✅ Nginx 不需要 .htaccess,伪静态全在配置里。


三、PHP 框架中的伪静态

ThinkPHP

  • Apache:直接放官方 .htaccess
  • Nginx:
location / {
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php?s=$1 last;
    }
}

Laravel

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

四、常见问题排查

  • 页面 404 → rewrite 模块没开 / AllowOverride 没设
  • 首页正常,内页 404 → 伪静态规则错误
  • Nginx 改完不生效 → 没 nginx -s reload

如果你能告诉我:

  • ✅ Ubuntu 版本
  • ✅ Apache 还是 Nginx
  • ✅ 用的什么 PHP 程序(原生 / ThinkPHP / Laravel)

我可以直接给你可复制的配置文件。

0 踩