在 Debian 上使用 Nginx 设置“伪静态”(URL Rewrite),本质是通过 rewrite 规则把动态请求(如 index.php?a=1)伪装成静态地址(如 /article/1.html)。
下面按常见场景给你说明。
核心指令:
rewrite 正则 目标URL [flag];
常用 flag:
last:重新匹配 locationbreak:不再匹配后续 rewriteredirect:302 跳转permanent:301 跳转通常:
/etc/nginx/nginx.conf
/etc/nginx/sites-enabled/
/etc/nginx/conf.d/
示例站点配置:
/etc/nginx/sites-enabled/default
把:
/article/123.html
转为:
/index.php?act=article&id=123
配置:
location / {
rewrite ^/article/([0-9]+)\.html$ /index.php?act=article&id=$1 last;
}
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
}
}
或(推荐):
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location / {
try_files $uri $uri/ /index.php?$args;
}
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
/news/2024/08/01.html
→
/index.php?m=news&y=2024&mo=08&d=01
rewrite ^/news/([0-9]{4})/([0-9]{2})/([0-9]{2})\.html$ /index.php?m=news&y=$1&mo=$2&d=$3 last;
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
nginx -t
systemctl reload nginx
查看 rewrite 是否生效:
rewrite_log on;
error_log /var/log/nginx/rewrite.log notice;
如果你能告诉我:
我可以直接给你一套可用配置。