温馨提示×

ubuntu php如何开启伪静态

小樊
40
2026-10-04 10:07:42
栏目: 编程语言

在 Ubuntu + PHP 环境下开启“伪静态”,通常取决于你使用的 Web 服务器(Apache 或 Nginx)。下面分别说明。


一、Apache 下开启伪静态(最常见)

1. 启用 rewrite 模块

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 修改站点配置,允许 .htaccess

编辑你的站点配置(如 /etc/apache2/sites-enabled/000-default.conf):

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

然后重启:

sudo systemctl restart apache2

3. 添加 .htaccess 规则(以 ThinkPHP / 通用为例)

在网站根目录创建 .htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>

✅ 这样就开启了伪静态。


二、Nginx 下开启伪静态

1. 修改站点配置

编辑 /etc/nginx/sites-enabled/default 或你的站点配置:

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

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

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

2. 测试并重启 Nginx

sudo nginx -t
sudo systemctl restart nginx

三、常见框架示例

ThinkPHP

  • Apache:使用上面 .htaccess
  • Nginx:
location / {
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php?s=$1 last;
    }
}

Laravel

Nginx:

try_files $uri $uri/ /index.php?$query_string;

四、检查是否生效

浏览器访问:

http://你的域名/xxx

不再出现 index.php/xxx 即成功。


如果你能告诉我:

  • 用的是 Apache 还是 Nginx
  • PHP 版本
  • 使用的框架(ThinkPHP / Laravel / WordPress 等)

我可以给你精确配置。

0 踩