简体   繁体   English

Nginx似乎使用重写,而与server_name无关

[英]nginx appears to use rewrite regardless of server_name

I have the following config file. 我有以下配置文件。

server {
  listen 80;
  server_name web.example.com;

  access_log  /var/www/example/shared/log/web.access.log;
  error_log  /var/www/example/shared/log/web.error.log debug;

  rewrite ^/(.*)$ http://www.example.net$request_uri; permanent;
}

When I make a request for curl -Ii -H "Host: example.com" http://example.com the above rewrite rule works. 当我请求curl -Ii -H“ Host:example.com” http://example.com时 ,上述重写规则有效。 (ARGH).. (哎呀)..

The server_name explicitly says "web.example.com" server_name明确显示“ web.example.com”

2014/11/18 22:49:20 [notice] 30694#0: 1868 "^/(. )$" matches "/", client: 1.2.3.4, server: web.example.com, request: "HEAD / HTTP/1.1", host: "example.com" 2014/11/18 22:49:20 [notice] 30694#0: *1868 rewritten redirect: " http://www.example.net/ ", client: 1.2.3.4, server: web.example.com, request: "HEAD / HTTP/1.1", host: "example.com" 2014/11/18 22:49:20 [notice] 30694#0: 1868“ ^ /(。)$”匹配“ /”,客户端:1.2.3.4,服务器:web.example.com,请求:“ HEAD / HTTP / 1.1”,主机:“ example.com” 2014/11/18 22:49:20 [notice] 30694#0:* 1868重写了重定向:“ http://www.example.net/ ”,客户端:1.2 .3.4,服务器:web.example.com,请求:“ HEAD / HTTP / 1.1”,主机:“ example.com”

Not present here is the other server { } configs. 这里没有其他服务器{}配置。 Xavier (below) pointed out that I had set default_server for listen: 443; Xavier(下)指出,我已经为监听设置了default_server:443; but not for listen: 80. (argh) 但不是为了听:80。(啊)

That's not the strict solution to the issue. 那不是解决问题的严格方法。

What's happening is that you have only one server block and it becomes the default server block for all requests, even the ones not matching the server name. 发生的情况是,您只有一个服务器块,它成为所有请求的默认服务器块,即使是与服务器名称不匹配的请求也是如此。 You simply need to add a default server block in your configuration : 您只需要在配置中添加一个默认服务器块:

server {
    listen 80 default_server;
} 

By the way, you have a typo (semicolon before permanent ) and you don't need a rewrite as you have specific regular expression. 顺便说一句,您有错别字(在permanent符号前用分号表示),并且由于具有特定的正则表达式而无需重写。 Use this instead : 使用它代替:

return 301 http://www.example.net$request_uri;

After a while... 过了一会儿...

I found that I needed the location / { } wrapped around it 我发现我需要将位置/ {}包裹起来

  server {
    listen 80;
    server_name web.example.com;

    access_log  /var/www/example/shared/log/web.access.log;
    error_log  /var/www/example/shared/log/web.error.log debug;

    location / {
      rewrite ^/(.*)$ http://www.example.net$request_uri permanent;
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM