温馨提示×

linux nginx如何设置伪静态

小樊
56
2026-10-19 14:15:44
栏目: 智能运维

在 Linux 下使用 Nginx 设置伪静态(URL Rewrite),通常是通过 rewrite 指令实现的。下面按常见场景给你说明。


一、什么是伪静态

伪静态就是把动态地址:

/index.php?a=1&b=2

伪装成静态地址:

/index/1/2.html

对 SEO 友好,看起来像静态页面。


二、Nginx 伪静态基本写法

1️⃣ 最简单 rewrite 示例

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

三、常见 CMS 伪静态规则

✅ WordPress

location / {
    try_files $uri $uri/ /index.php?$args;
}

✅ Typecho

location / {
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php$1 last;
    }
}

✅ Discuz! X

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;

四、完整示例(PHP + 伪静态)

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),告诉我,我可以给你对应的精确伪静态规则。

0 踩