在 LNMP(Linux + Nginx + MySQL + PHP) 环境下,伪静态通常是通过 Nginx 的 rewrite 规则 实现的。下面按常见场景给你说明。
Nginx 本身不支持 .htaccess,伪静态需要在 站点配置文件 或 伪静态规则文件 中设置 rewrite。
常见路径:
/usr/local/nginx/conf/vhost/域名.conf/usr/local/nginx/conf/rewrite/域名.conf如果你用的是 LNMP 一键安装包:
lnmp vhost add
添加站点时会问:
Add rewrite rule? (y/n)
选 y,然后会让你选择:
选对应程序即可自动生成伪静态。
✅ 已存在站点可重新设置:
lnmp vhost rewrite 域名
vi /usr/local/nginx/conf/vhost/yourdomain.conf
示例(WordPress):
server {
listen 80;
server_name yourdomain.com;
root /home/wwwroot/yourdomain;
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;
}
}
在 yourdomain.conf 中引入:
include rewrite/wordpress.conf;
创建规则文件:
vi /usr/local/nginx/conf/rewrite/wordpress.conf
内容:
rewrite ^/(.*)$ /index.php/$1 last;
或 WordPress 常用:
try_files $uri $uri/ /index.php?$args;
try_files $uri $uri/ /index.php?$args;
if (!-f $request_filename){
rewrite ^/(.*)$ /index.php/$1 last;
}
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?s=$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;
nginx -t
lnmp nginx reload
或:
systemctl reload nginx
❌ 伪静态不生效
reload nginxrewrite 写错 last / break❌ 出现 404
try_files 路径不对root 目录配置错误如果你告诉我:
我可以直接帮你写一份可用的伪静态配置。