在 Linux 下使用 Nginx 设置伪静态(URL Rewrite),通常是通过 rewrite 指令实现的。下面按常见场景给你说明。
伪静态就是把动态地址:
/index.php?a=1&b=2
伪装成静态地址:
/index/1/2.html
对 SEO 友好,看起来像静态页面。
server {
listen 80;
server_name example.com;
root /www/wwwroot/example;
index index.php index.html;
location / {
# 伪静态规则
rewrite ^/news/(\d+)\.html$ /news.php?id=$1 last;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
}
}
访问:
/news/123.html
实际访问:
/news.php?id=123
location / {
try_files $uri $uri/ /index.php?$args;
}
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php$1 last;
}
}
rewrite ^/topic-(.+)\.html$ /portal.php?mod=topic&topic=$1 last;
rewrite ^/forum-(\d+)-(\d+)\.html$ /forum.php?mod=forumdisplay&fid=$1&page=$2 last;
rewrite ^/thread-(\d+)-(\d+)-(\d+)\.html$ /forum.php?mod=viewthread&tid=$1&page=$2 last;
server {
listen 80;
server_name www.example.com;
root /www/wwwroot/example;
index index.php index.html;
location / {
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
}
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
nginx -t # 检查配置
systemctl reload nginx
# 或
service nginx reload
✅ last:继续匹配 location
✅ break:不再匹配 rewrite
✅ if (!-e $request_filename):文件不存在才重写
❌ 不要滥用 if,容易出问题
如果你用的是 宝塔 / 1Panel / 某个具体程序(如 ThinkPHP、Laravel),告诉我,我可以给你对应的精确伪静态规则。