温馨提示×

debian nginx怎样设置伪静态

小樊
33
2026-10-21 02:25:02
栏目: 智能运维

在 Debian 上用 Nginx 设置“伪静态”(URL Rewrite),通常不是像 Apache 那样用 .htaccess,而是在 Nginx 的站点配置文件里写 rewrite 规则。

下面按常见场景给你说明。


一、配置文件位置

Debian 下 Nginx 站点配置一般在:

/etc/nginx/sites-available/
/etc/nginx/sites-enabled/

通常你会编辑:

/etc/nginx/sites-available/default
# 或你自己的站点配置

二、基础 rewrite 语法

rewrite 正则 URL [flag];

常用 flag:

  • last:继续执行其他 location
  • break:停止 rewrite
  • redirect:302 跳转
  • permanent:301 永久跳转

三、常见伪静态示例

1️⃣ 把 /index.php?a=1 伪装成 /a/1.html

location / {
    rewrite ^/a/(\d+)\.html$ /index.php?a=$1 last;
}

访问:

/a/123.html

实际执行:

/index.php?a=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(单入口)

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

四、完整示例(Debian + PHP + Nginx)

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

五、修改后必须操作

nginx -t        # 检查配置
systemctl reload nginx

六、注意事项(很重要)

❌ 不要随便用 if ✅ 优先使用 try_files ❌ Nginx 没有 .htaccess ✅ 伪静态依赖后端程序解析参数


如果你能告诉我:

  • 用的是 什么程序(WordPress / ThinkPHP / 自写 PHP)
  • 想要 什么样的 URL 变成什么样

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

0 踩