在 Debian 上使用 Nginx 做伪静态(URL Rewrite),通常是指把动态 URL(如 index.php?id=1)重写成更友好的静态形式(如 /article/1.html 或 /article/1)。下面按常见场景说明。
sudo apt update
sudo apt install nginx
/etc/nginx/sites-available/
/etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
主要使用:
rewritetry_files语法示例:
rewrite 正则表达式 目标URL [flag];
常见 flag:
last:重新匹配 locationbreak:停止 rewriteredirect:302 跳转permanent:301 永久跳转/article/123.html 转发到 PHPlocation / {
rewrite ^/article/([0-9]+)\.html$ /article.php?id=$1 last;
}
访问:
/article/123.html
实际执行:
/article.php?id=123
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?$query_string;
}
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
}
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
}
查看重写是否生效:
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
开启 rewrite 日志(调试用):
error_log /var/log/nginx/rewrite.log notice;
rewrite_log on;
❌ if 滥用(Nginx 官方不推荐)
❌ rewrite 写成死循环
❌ PHP 未正确解析
❌ 忘记 nginx -t 和 reload
如果你能提供:
我可以帮你直接写一份可用的 Nginx 配置。