温馨提示×

ubuntu php怎样配置伪静态

小樊
47
2026-09-04 12:45:33
栏目: 编程语言

在 Ubuntu 下配置 PHP 的“伪静态”(通常指 URL Rewrite,如 /index.php?a=1/a/1.html),主要分为 Web 服务器配置PHP 程序配合 两部分。常见情况是使用 ApacheNginx


一、Apache 下配置伪静态(最常用)

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>

重启 Apache:

sudo systemctl restart apache2

3. 创建 .htaccess(伪静态规则)

在网站根目录(如 /var/www/html)创建:

nano /var/www/html/.htaccess

示例(ThinkPHP / 通用):

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

或常见 .html 伪静态:

RewriteRule ^article-([0-9]+).html$ article.php?id=$1

二、Nginx 下配置伪静态

1. 编辑站点配置

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

2. 配置 rewrite

server {
    listen 80;
    server_name localhost;
    root /var/www/html;

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

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

3. 重启 Nginx

sudo systemctl restart nginx

三、PHP 程序端配合

伪静态只是“转发 URL”,PHP 仍需正确解析

  • 使用 $_GET
  • 或使用框架路由(Laravel / ThinkPHP)

示例:

// article.php
$id = $_GET['id'];
echo $id;

四、常见框架伪静态示例

  • ThinkPHP:Apache 用 .htaccess,Nginx 用 try_files
  • WordPress:标准 .htaccess
  • Laravel:Nginx try_files

五、排查问题

# Apache 是否开启 rewrite
apache2ctl -M | grep rewrite

# Nginx 配置是否正确
nginx -t

如果你能告诉我:

  • ✅ 用的是 Apache 还是 Nginx
  • ✅ PHP 版本
  • ✅ 使用的是 原生 PHP / ThinkPHP / Laravel / WordPress

我可以直接给你 可复制的完整配置

0