一、Nginx 伪静态基础配置
在使用伪静态前,需要确保 Nginx 已安装
rewrite
模块。通常在编译 Nginx 时会默认安装,可通过以下命令检查:nginx -V 2>&1 | grep rewrite
若未安装,需重新编译 Nginx 并添加
--with-http_rewrite_module
参数。二、常见场景伪静态规则
1. 去除 URL 中的 index.php
动态网站(如 WordPress、Discuz!)常使用
index.php
作为入口文件,伪静态可隐藏该文件:location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php$1 last;
break;
}
}
2. 支持 .html/.htm 后缀伪静态
将动态 URL 转换为以
.html
或 .htm
结尾的静态形式:location / {
if (!-e $request_filename) {
rewrite ^(.*)\.html$ $1.php last;
rewrite ^(.*)\.htm$ $1.php last;
rewrite ^(.*)$ /index.php$1 last;
break;
}
}
3. WordPress 伪静态配置
WordPress 典型伪静态规则,支持固定链接功能:
location / {
try_files $uri $uri/ /index.php?$args;
}
4. 电商平台分类页伪静态
将
category.php?id=1
转换为 category/1.html
:rewrite ^/category/(\d+)\.html$ /category.php?id=$1 last;
5. 文章详情页伪静态
将
article.php?id=100
转换为 article/2025/05/100.html
(含日期路径):rewrite ^/article/(\d{4})/(\d{2})/(\d+)\.html$ /article.php?year=$1&month=$2&id=$3 last;
6. 强制 HTTPS 伪静态
将 HTTP 请求重定向到 HTTPS(需先配置 SSL 证书):
server {
listen 80;
server_name example.com;
rewrite ^(.*)$ https://$server_name$1 permanent;
}
7. 移动端适配伪静态
根据 UA 标识重定向到移动端页面:
if ($http_user_agent ~* "Android|iPhone|iPad|Mobile") {
rewrite ^(.*)$ http://m.example.com$1 permanent;
}
三、伪静态指令详解
伪静态配置中常用的 Nginx 指令:
指令 | 说明 |
---|---|
rewrite |
重写 URL,支持正则匹配和反向引用(如 $1 表示第一个捕获组) |
if |
条件判断,检查文件是否存在、UA 标识等 |
try_files |
按顺序检查文件是否存在,不存在则执行最后一个参数(如重定向到 index.php) |
last |
完成当前 rewrite 规则,不再执行后续规则 |
permanent |
返回 301 永久重定向,利于 SEO |
break |
终止当前 location 的处理,不再执行后续规则 |
四、配置注意事项
-
规则顺序:rewrite 规则按从上到下的顺序执行,匹配即停止,需按优先级排序(精确匹配在前,泛匹配在后)。
-
性能影响:过多复杂的正则匹配会消耗 CPU 资源,建议减少嵌套和冗余规则。
-
调试方法:
- 开启 Nginx 日志:
log_format rewrite_log '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" ' 'rewrite: $rewrite_status';
- 在 rewrite 规则中添加
rewrite_log on;
记录匹配过程。
- 开启 Nginx 日志:
-
测试工具:使用 Rewrite Tester 在线验证规则有效性。
五、完整配置示例
以 WordPress 站点为例,完整的 Nginx 伪静态配置:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/wordpress;
index index.php index.html index.htm;
# 强制 www 域名
if ($host !~* ^www\.example\.com$) {
rewrite ^(.*)$ http://www.example.com$1 permanent;
}
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 7d;
add_header Cache-Control "public";
}
}
通过合理配置伪静态规则,可有效提升网站的可访问性和 SEO 效果。配置完成后,建议使用
nginx -t
检查配置语法,并重启 Nginx 使规则生效:systemctl restart nginx
。