debian

Debian Nginx URL重写规则示例

小樊
41
2025-10-28 16:15:52
栏目: 智能运维

在Debian上使用Nginx进行URL重写时,通常会使用rewrite指令。以下是一个基本的示例,展示了如何在Nginx配置文件中使用rewrite指令来实现URL重写。

假设我们有一个网站,原始的URL结构是http://example.com/user.php?id=123,我们希望将其重写为更友好的URL结构http://example.com/user/123

  1. 打开Nginx配置文件。通常位于/etc/nginx/sites-available/目录下,例如default或自定义的配置文件。
sudo nano /etc/nginx/sites-available/default
  1. server块中添加或修改location块,以包含重写规则。
server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location /user/ {
        rewrite ^/user/(\d+)$ /user.php?id=$1 last;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
    }
}

在这个示例中:

  1. 保存并关闭配置文件。

  2. 测试Nginx配置是否正确。

sudo nginx -t
  1. 如果配置测试通过,重新加载Nginx以应用更改。
sudo systemctl reload nginx

现在,访问http://example.com/user/123将会被重写为http://example.com/user.php?id=123

请根据你的具体需求调整重写规则和配置。

0
看了该问题的人还看了