在 CentOS 上开启 PHP 伪静态(rewrite),核心就是:
开启 Apache/Nginx 的 rewrite 模块 + 配置规则。下面分别说明常见场景。
httpd -v
# 或
apachectl -v
如果没装:
yum install httpd -y
systemctl start httpd
systemctl enable httpd
CentOS 7/8 默认已编译 mod_rewrite,只需要启用:
vim /etc/httpd/conf/httpd.conf
找到:
#LoadModule rewrite_module modules/mod_rewrite.so
去掉 #:
LoadModule rewrite_module modules/mod_rewrite.so
找到站点目录配置(通常在 <Directory> 中):
<Directory "/var/www/html">
AllowOverride None
</Directory>
改为:
<Directory "/var/www/html">
AllowOverride All
</Directory>
✅ AllowOverride None → All 是最容易遗漏的一步
systemctl restart httpd
.htaccess(PHP 伪静态规则)在网站根目录创建:
vim /var/www/html/.htaccess
示例(通用):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
如果是 ThinkPHP / Laravel / WordPress,规则略有不同,我也可以帮你写。
nginx -v
vim /etc/nginx/conf.d/default.conf
或:
vim /etc/nginx/nginx.conf
示例(通用 PHP 伪静态):
location / {
try_files $uri $uri/ /index.php?$args;
}
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;
}
✅ Nginx 没有 .htaccess,只能在配置文件中写
systemctl restart nginx
✅ 检查:
AllowOverride Allsetenforce 0
临时关闭 SELinux 测试:
vim /etc/selinux/config
SELINUX=disabled
| 环境 | 是否需要 .htaccess | 关键操作 |
|---|---|---|
| Apache | ✅ 是 | AllowOverride All |
| Nginx | ❌ 否 | try_files / rewrite |
| PHP | ✅ 支持 | 无需额外开启 |
如果你能告诉我:
我可以直接给你对应的完整配置文件 ✅