温馨提示×

debian nginx如何做伪静态

小樊
35
2026-10-03 14:23:50
栏目: 智能运维

在 Debian 上使用 Nginx 做伪静态(URL Rewrite),通常是指把动态 URL(如 index.php?id=1)重写成更友好的静态形式(如 /article/1.html 或 /article/1)。下面按常见场景说明。


一、基础前提

  1. 已安装 Nginx(Debian):
sudo apt update
sudo apt install nginx
  1. 网站配置文件位置:
/etc/nginx/sites-available/
/etc/nginx/sites-enabled/
  1. 修改配置后务必测试并重启:
sudo nginx -t
sudo systemctl reload nginx

二、Nginx 伪静态核心指令

主要使用:

  • rewrite
  • try_files

语法示例:

rewrite 正则表达式 目标URL [flag];

常见 flag:

  • last:重新匹配 location
  • break:停止 rewrite
  • redirect:302 跳转
  • permanent:301 永久跳转

三、常见伪静态示例

1️⃣ 把 /article/123.html 转发到 PHP

location / {
    rewrite ^/article/([0-9]+)\.html$ /article.php?id=$1 last;
}

访问:

/article/123.html

实际执行:

/article.php?id=123

2️⃣ ThinkPHP 伪静态(常见)

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

或推荐写法(更安全):

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

3️⃣ WordPress 伪静态

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

4️⃣ 隐藏 index.php(CI / Laravel)

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

5️⃣ 强制 https + 伪静态

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;
    }
}

四、完整示例(PHP 网站)

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


如果你能提供:

  • 使用的程序(WordPress / ThinkPHP / 自写 PHP)
  • 原始 URL 和目标 URL 示例

我可以帮你直接写一份可用的 Nginx 配置。

0 踩