温馨提示×

LNMP如何设置伪静态规则

小樊
46
2026-07-10 23:00:24
栏目: 编程语言

LNMP(Linux + Nginx + MySQL + PHP) 环境下,伪静态本质上就是 Nginx 的 rewrite 规则。不同程序(WordPress、ThinkPHP、Laravel、Discuz 等)规则不同,但设置位置和方法基本一致。

下面我一整套 通用做法 + 常见程序示例,你可以直接使用。


一、LNMP 伪静态设置位置

1️⃣ 网站配置文件位置

LNMP 默认站点配置一般在:

/usr/local/nginx/conf/vhost/域名.conf

例如:

/usr/local/nginx/conf/vhost/example.com.conf

2️⃣ 伪静态规则写在哪里?

写在 server {} 里的 location / {},例如:

server {
    listen 80;
    server_name example.com;
    root /home/wwwroot/example.com;
    index index.php index.html;

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

    location ~ \.php$ {
        fastcgi_pass  unix:/tmp/php-cgi.sock;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
}

rewrite 规则一般放在 location / {}


二、常见伪静态规则示例


✅ WordPress(最常用)

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

LNMP 一键包默认支持


✅ ThinkPHP 5 / 6

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

或者(推荐):

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

✅ Laravel

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

✅ Discuz! X3.4

rewrite ^/topic-(.+)\.html$ /portal.php?mod=topic&topic=$1 last;
rewrite ^/article-([0-9]+)-([0-9]+)\.html$ /portal.php?mod=view&aid=$1&page=$2 last;
rewrite ^/forum-(\w+)-([0-9]+)\.html$ /forum.php?mod=forumdisplay&fid=$1&page=$2 last;
rewrite ^/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /forum.php?mod=viewthread&tid=$1&extra=page%3D$3&page=$2 last;
rewrite ^/group-([0-9]+)-([0-9]+)\.html$ /group.php?mod=group&fid=$1&page=$2 last;
rewrite ^/space-(username|uid)-(.+)\.html$ /home.php?mod=space&$1=$2 last;
rewrite ^/blog-([0-9]+)-([0-9]+)\.html$ /home.php?mod=space&uid=$1&do=blog&id=$2 last;
rewrite ^/archiver/(fid|tid)-([0-9]+)\.html$ /archiver/index.php?action=$1&value=$2 last;
rewrite ^/([a-z]+)-(.+)\.html$ /$1.php?rewrite=$2 last;

✅ Typecho

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

三、LNMP 一键包专用方式(推荐)

如果你用的是 LNMP 一键安装包,可以直接用:

lnmp vhost add

或者手动指定伪静态规则文件:

include rewrite/wordpress.conf;

路径在:

/usr/local/nginx/conf/rewrite/

例如:

/usr/local/nginx/conf/rewrite/wordpress.conf

四、修改后一定要做的事

✅ 1. 检查 Nginx 配置

nginx -t

✅ 2. 重载 Nginx

service nginx reload

或:

systemctl reload nginx

五、常见问题排查

❌ 伪静态不生效?

✔ 检查:

  • 规则是否写在 正确 server 段
  • 是否执行了 nginx reload
  • 程序后台是否开启伪静态
  • 是否和 try_files 冲突

❌ 出现 404?

  • Nginx 没匹配到 rewrite
  • PHP 没解析
  • 规则顺序错误

六、我可以帮你定制

如果你愿意,可以告诉我:

  1. LNMP 版本
  2. 网站程序(WordPress / TP / Laravel / 其他)
  3. 是否需要多站点 / 二级目录

我可以直接给你 完整可用的 Nginx 配置文件

0