【问题标题】:Simple nginx redirect doesn't match简单的 nginx 重定向不匹配
【发布时间】:2019-07-27 14:16:51
【问题描述】:

我最初试图进行复杂的 URL 重写,但我无法正常工作,因此将其剥离回一个简单的 URL 重定向,它肯定可以工作,而不是抛出 404。

对 [any_scheme]://www.mydomain.com/google 的请求应重定向到 https://www.google.com/

nginx.conf (未发布,因为它不包含服务器块所以不能冲突?)

mydomain.com.conf:

server {
    server_name www.mydomain.com;
    root /home/mydomain/public_html;
    index index.php index.html index.htm;

    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;

    ssl_certificate /home/mydomain/ssl.combined;
    ssl_certificate_key /home/mydomain/ssl.key;

    access_log /var/log/virtualmin/mydomain.com_access_log;
    error_log /var/log/virtualmin/mydomain.com_error_log;

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

    location = /google {
        return 302 https://www.google.com/;
    }

    #rogue .htaccess files caught here
    location ~ /\.ht {
        deny all;
    }
}

#force non-www. to www.
server {
    server_name mydomain.com;
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;
    return 301 $scheme://www.mydomain.com$request_uri;
}

【问题讨论】:

  • 试过nginx -t && service nginx reload ?
  • @DanilaVershinin 是的,每次更改。其他地方一定有冲突,因为我认为这个配置很干净
  • 有没有对应这个404响应的访问日志条目?
  • xxxx - - [06/Mar/2019:01:45:39 +0000] "GET /google/ HTTP/1.1" 404 193 "-" "Mozilla/5.0 (Linux; Android 7.1. 2; Swift 2 X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.76 Mobile Safari/537.36"
  • 我想知道www.mydomain.com 的其他位置是否有效?你检查了吗?

标签: nginx nginx-location


【解决方案1】:
  • 使用curl -v 调试服务器的运行状况。

  • 你使用sites-available/sites-enabled吗?别。见https://serverfault.com/a/870709/110020sites-available / sites-enabled 是非标准的,是邪恶的,不要使用它,改用conf.d

  • 确保您确实重新加载了 nginx。见https://stackoverflow.com/a/21297545/1122270。直接试试sudo nginx -s reloadsudo pkill -HUP nginx

  • 检查error_logaccess_log。确保活动日期与您提出的新请求相匹配。我建议打开几个终端窗口,并在每个窗口中执行 tail -f,然后按几次 return 将新输入与旧输入分开,然后再执行请求。

  • 您是否在 nginx 之上使用了任何额外的代理?这些可能是问题的原因。

【讨论】:

  • 谢谢,我认为 sudo nginx -s reload 成功了。我一直在使用systemctl reload nginx,我相信它基本上是一样的,所以不确定为什么这次它起作用了,但它确实起作用了。我也会在sites-enabled 上听取您的建议。作为记录,我使用的是 Ubuntu 16.04 LEMP 的数字海洋图像。再次感谢。
【解决方案2】:

根据您的日志条目:您正在请求 /google/(注意尾部斜杠),但这与 /google 位置不匹配,因为那里没有尾部斜杠。

所以你需要两个完全匹配的位置:

location = /google {
    return 302 https://www.google.com/;
}

location = /google/ {
    return 302 https://www.google.com/;
}

【讨论】:

  • 对不起,我的日志文件行不正确,我一直在测试有无斜线并发布了错误的行。即使规则中有斜线和 URL 中的测试斜线,我也会得到相同的响应。有没有其他方法可以追踪问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2023-03-11
  • 2021-09-15
相关资源
最近更新 更多