温馨提示×

centos apache2如何设伪静

小樊
42
2026-09-30 03:17:13
栏目: 智能运维

在 CentOS 上通常使用 Apache(httpd) 而不是 apache2(那是 Ubuntu/Debian 的叫法)。下面以 CentOS 7/8 + Apache + PHP 为例,说明如何设置伪静态(Rewrite)。


一、开启 mod_rewrite 模块

  1. 检查模块是否已加载
httpd -M | grep rewrite

如果有 rewrite_module,说明已开启。

  1. 如果没有,编辑 Apache 配置
vi /etc/httpd/conf/httpd.conf

确保这一行没有被注释:

LoadModule rewrite_module modules/mod_rewrite.so

二、允许目录使用 .htaccess

找到你的站点配置(或虚拟主机):

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

改成:

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

如果是虚拟主机,修改对应的 <VirtualHost> 里的 <Directory>


三、重启 Apache

systemctl restart httpd

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

在网站根目录创建或编辑 .htaccess:

vi /var/www/html/.htaccess

常见示例

1. 所有请求转发到 index.php(ThinkPHP / Laravel 常用)

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

2. 将 /news/123 转为 /news.php?id=123

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

3. 隐藏 .php 后缀

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

五、常见问题

1. 伪静态不生效

  • 检查 AllowOverride All
  • 检查 .htaccess 是否在正确目录
  • 查看错误日志:
tail -f /var/log/httpd/error_log

2. SELinux 导致无法读取 .htaccess

setsebool -P httpd_can_network_connect 1

六、如果你用的是 Nginx(补充)

CentOS 上很多人实际用的是 Nginx,如果你需要 Nginx 伪静态规则,也可以告诉我。


如果你能说明:

  • 使用的是 Apache 还是 Nginx
  • 使用的是 ThinkPHP / Laravel / WordPress / 自写程序

我可以直接给你对应可用的伪静态规则。

0 踩