温馨提示×

CentOS怎么开启PHP伪静态

小樊
35
2026-07-08 03:04:33
栏目: 编程语言

CentOS 上开启 PHP 伪静态(rewrite),核心就是:
开启 Apache/Nginx 的 rewrite 模块 + 配置规则。下面分别说明常见场景。


一、Apache + PHP(最常见)

1️⃣ 确认 Apache 已安装

httpd -v
# 或
apachectl -v

如果没装:

yum install httpd -y
systemctl start httpd
systemctl enable httpd

2️⃣ 开启 rewrite 模块

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

3️⃣ 允许 .htaccess 生效(关键)

找到站点目录配置(通常在 <Directory> 中):

<Directory "/var/www/html">
    AllowOverride None
</Directory>

改为:

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

AllowOverride None → All 是最容易遗漏的一步


4️⃣ 重启 Apache

systemctl restart httpd

5️⃣ 创建 .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 + PHP(LNMP 常见)

1️⃣ 确认 Nginx 已安装

nginx -v

2️⃣ 修改站点配置

vim /etc/nginx/conf.d/default.conf

或:

vim /etc/nginx/nginx.conf

3️⃣ 添加 rewrite 规则

示例(通用 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,只能在配置文件中写


4️⃣ 重启 Nginx

systemctl restart nginx

三、常见问题排查

❌ 伪静态不生效

✅ 检查:

  • Apache:AllowOverride All
  • Nginx:是否重载配置
  • 是否清空浏览器缓存
  • 是否修改的是正确配置文件

❌ 403 / 404

setenforce 0

临时关闭 SELinux 测试:

vim /etc/selinux/config
SELINUX=disabled

四、总结速查表

环境 是否需要 .htaccess 关键操作
Apache ✅ 是 AllowOverride All
Nginx ❌ 否 try_files / rewrite
PHP ✅ 支持 无需额外开启

如果你能告诉我:

  • CentOS 版本(7 / 8 / Stream)
  • Apache 还是 Nginx
  • 用的是 ThinkPHP / Laravel / WordPress / 原生 PHP

我可以直接给你对应的完整配置文件

0