温馨提示×

centos怎么配apache伪

小樊
42
2026-10-26 11:36:58
栏目: 智能运维

你问的应该是 CentOS 下配置 Apache 伪静态(Rewrite),下面给你一份常用、可直接用的步骤。


一、确认 Apache 已安装

httpd -v

如果没有:

yum install httpd -y
systemctl start httpd
systemctl enable httpd

二、开启 mod_rewrite 模块

CentOS 默认一般已加载,确认一下:

httpd -M | grep rewrite

看到 rewrite_module 就说明已开启。

如未开启,编辑:

vi /etc/httpd/conf/httpd.conf

确保有这一行(去掉前面 #):

LoadModule rewrite_module modules/mod_rewrite.so

三、允许目录使用 .htaccess(关键)

编辑虚拟主机或主配置:

vi /etc/httpd/conf/httpd.conf

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

找到你的网站目录,改成:

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

然后重启 Apache:

systemctl restart httpd

四、写伪静态规则(.htaccess)

在网站根目录创建:

vi /var/www/html/.htaccess

示例 1:全部转发到 index.php(常见框架)

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

示例 2:把 /news/1 伪静态成 /news.php?id=1

RewriteEngine On
RewriteRule ^news/([0-9]+)$ news.php?id=$1 [L]

五、常见坑

  1. AllowOverride 不是 All → 伪静态不生效
  2. SELinux 开启导致 403
    setsebool -P httpd_can_network_connect 1
    
  3. 改完配置一定要:
    systemctl restart httpd
    

如果你用的是 ThinkPHP / Laravel / WordPress / Discuz,可以直接告诉我,我给你对应现成规则。

0 踩