Nginx http将httpsredirect到第一个server_name

我有一个这2个服务器块在我的nginx/sites-enabled/application.conf

 upstream myapplication { server 127.0.0.1:8081; } server { listen 80; server_name app1.example.net app2.example.net app3.example.net; return 301 https://$server_name$request_uri; } server { listen 80; server_name app1.example.net app2.example.net app3.example.net; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_certificate /etc/ssl/certs/example_net.crt; ssl_certificate_key /etc/ssl/certs/example_net.key; ssl_verify_client off; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers RC4:HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; proxy_ssl_session_reuse off; location /apply { rewrite ^/apply(.*) $scheme://$server_name/?$query_string? permanent; } location / { proxy_pass http://myapplication; } } 

这是我的nginx/nginx.conf :用户www-data; worker_processes auto; pid /run/nginx.pid;

 events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; disable_symlinks off; # server_tokens off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # Proxy redirect ## proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwared-For $proxy_add_x_forwarded_for; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; gzip_disable "msie6"; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } 

我遇到的问题是,如果我访问http app2.example.net我redirect到https app1.example.net时,它应该redirect到https app2.example.net,但是,如果我直接去https app2.example .net然后工作正常。

我在configuration中错过了什么?

使用$server_name将始终使用块中的第一个。

你需要使用$http_host来获取请求主机。

或者只是为每个域做3块将做的伎俩。

Nginx将selectserver_namevariables的第一个条目。 尝试使用$http_host来代替,看看是否有帮助。

$http_host将直接从HTTP请求中获取请求主机。 看到你使用的是虚拟主机,你只能得到包含这些名字的服务器块的请求,所以HTTP请求将总是包含这3个主机中的一个。