温馨提示×

centos php怎样配置伪静态

小樊
45
2026-09-02 18:30:14
栏目: 编程语言

在 CentOS 上配置 PHP 伪静态,通常是 结合 Web 服务器(Apache 或 Nginx) 来实现的。下面分别说明两种常见方式。


一、Apache + PHP(最常见)

1. 开启 mod_rewrite 模块

httpd -M | grep rewrite

如果没有,开启:

vi /etc/httpd/conf/httpd.conf

确保以下行没有被注释:

LoadModule rewrite_module modules/mod_rewrite.so

2. 修改虚拟主机或目录配置

找到你的站点配置(如 /etc/httpd/conf.d/xxx.conf):

<VirtualHost *:80>
    DocumentRoot /var/www/html
    ServerName www.example.com

    <Directory "/var/www/html">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

关键是 AllowOverride All

3. 添加 .htaccess(伪静态规则)

在网站根目录创建 .htaccess:

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

4. 重启 Apache

systemctl restart httpd

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

1. 修改 Nginx 配置

编辑站点配置(如 /etc/nginx/conf.d/default.conf):

server {
    listen 80;
    server_name www.example.com;
    root /usr/share/nginx/html;
    index index.php index.html;

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

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

2. 重启 Nginx

systemctl restart nginx

三、常见框架示例

ThinkPHP

Apache

RewriteRule ^(.*)$ index.php/$1 [L]

Nginx

location / {
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php?s=$1 last;
    }
}

Laravel

Nginx 推荐:

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

四、排查问题

  • 404:检查 AllowOverride 或 try_files
  • 500:查看 /var/log/httpd/error_log 或 /var/log/nginx/error.log
  • PHP 未解析:确认 php-fpm 已启动

如果你能告诉我:

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

我可以给你更精确的配置。

0 踩