温馨提示×

centos如何设置apache伪静态

小樊
49
2026-08-03 22:34:45
栏目: 智能运维

CentOS 上设置 Apache 伪静态(URL Rewrite),通常是指使用 mod_rewrite 模块来实现。下面按常见场景一步步说明。


一、确认 Apache 已安装并启用 mod_rewrite

1. 检查 Apache 是否安装

httpd -v
# 或
apachectl -v

如果没有安装:

yum install httpd -y
systemctl start httpd
systemctl enable httpd

2. 检查 mod_rewrite 模块是否启用

httpd -M | grep rewrite

如果看到:

rewrite_module (shared)

说明已启用。

CentOS 7/8 默认已启用 mod_rewrite
如果没有,可手动加载(一般不用):

vim /etc/httpd/conf/httpd.conf

确认有:

LoadModule rewrite_module modules/mod_rewrite.so

二、允许 .htaccess 伪静态(关键)

Apache 默认可能不允许使用 .htaccess

1. 编辑虚拟主机或主配置

vim /etc/httpd/conf/httpd.conf

找到你的网站目录配置(如 /var/www/html):

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

✅ 修改为:

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

⚠️ AllowOverride None → All 是伪静态生效的关键


2. 重启 Apache

systemctl restart httpd

三、创建伪静态规则(.htaccess)

进入网站根目录:

cd /var/www/html

创建或编辑 .htaccess

vim .htaccess

示例 1:基础伪静态(开启 Rewrite)

RewriteEngine On

# 将 index.php?id=1 转为 /1.html
RewriteRule ^([0-9]+)\.html$ index.php?id=$1 [L]

示例 2:隐藏 index.php(ThinkPHP / Laravel 常用)

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

示例 3:WordPress 伪静态

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

四、SELinux 问题(CentOS 常见坑)

如果配置正确但仍 404,可能是 SELinux 限制。

1. 临时关闭 SELinux(测试用)

setenforce 0

2. 永久关闭(不推荐生产)

vim /etc/selinux/config
SELINUX=disabled

3. 正确做法(推荐)

允许 Apache 使用伪静态:

setsebool -P httpd_can_network_connect 1
setsebool -P httpd_enable_homedirs 1

五、测试是否生效

访问:

http://服务器IP/1.html

如果正确跳转到:

index.php?id=1

✅ 伪静态成功


六、常见问题排查

问题 解决方案
404 检查 AllowOverride All
500 .htaccess 语法错误
规则不生效 确认 mod_rewrite 已加载
修改无效 重启 httpd

七、总结(最简流程)

yum install httpd -y
systemctl start httpd
vim /etc/httpd/conf/httpd.conf
# AllowOverride None → All
systemctl restart httpd

然后创建 .htaccess 并写 RewriteRule 即可 ✅


如果你用的是 CentOS 7 / 8 / 9宝塔面板ThinkPHP / Laravel / WordPress,可以告诉我,我可以给你对应环境的精确配置

0