温馨提示×

Debian Nginx如何设置伪静态

小樊
32
2026-08-05 12:30:50
栏目: 智能运维

Debian 下通过 Nginx 设置伪静态(URL Rewrite),通常用于 隐藏 index.php美化 URL,常见于 WordPress、Typecho、Laravel、ThinkPHP 等程序。

下面按通用做法 + 常见程序示例说明。


一、Nginx 伪静态基本原理

Nginx 没有 Apache 的 .htaccess,伪静态通过:

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

rewrite 规则实现。


二、Debian 下 Nginx 配置文件位置

一般路径:

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

网站配置通常在:

/etc/nginx/sites-available/your-site

三、通用伪静态(隐藏 index.php)

1️⃣ 编辑站点配置

sudo nano /etc/nginx/sites-available/default

2️⃣ 添加伪静态规则

server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/html;
    index index.php index.html;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }
}

✅ 适用于大多数 PHP 程序


四、常见程序伪静态规则

✅ WordPress

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

✅ Typecho

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

✅ Laravel

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

✅ ThinkPHP 6

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

五、重载 Nginx 生效

sudo nginx -t
sudo systemctl reload nginx

六、常见错误排查

❌ 404 伪静态无效

  • 检查 root 路径是否正确
  • 确认 index.php 存在
  • 确认 PHP-FPM 正常运行

❌ rewrite 不生效

  • 是否在 正确 location
  • 是否忘记 lastbreak

七、总结一句话

Debian + Nginx 伪静态 ≠ .htaccess

try_filesrewrite 写在 server {} 配置里,然后 nginx -s reload


如果你使用的是 某个具体程序(如 WordPress / Typecho / Laravel / 自建 PHP),可以告诉我,我可以给你精确配置

0