Nginx

在同一個 nginx 伺服器下定義兩個監聽(80 和 443)是否正確?

  • September 6, 2019

像這樣在相同的情況下定義listen(80和 443 )是否正確server {}

另一種方法是為server{}我知道可以的每個埠定義兩個單獨的埠。

server {

   listen       80 default_server;
   server_name  example.com;
   root         /usr/share/nginx/html;

   location / {

   }


   listen example.com:443 ssl; # <<< !!!

   ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; 
   ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; 
   include /etc/letsencrypt/options-ssl-nginx.conf; 
   ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;         
}

據我記得,是的。在文件中也這麼說(下面的連結):

單個 HTTP/HTTPS 伺服器

可以配置一個同時處理 HTTP 和 HTTPS 請求的伺服器:

server {
   listen              80;
   listen              443 ssl;
   server_name         www.example.com;
   ssl_certificate     www.example.com.crt;
   ssl_certificate_key www.example.com.key;
   ...
}

原始碼:https ://nginx.org/en/docs/http/configuring_https_servers.html

允許偵聽同server一塊上的多個埠,但是否要這樣做取決於您的目標。

當我有以下一組域並且我想用https://www.example.com作主域時,我個人使用以下設置:

http://example.com
https://example.com
http://www.example.com
https://www.example.com

server``example.com埠 80 和 443的塊:

server {
   server_name example.com;
   listen 80;
   listen 443 ssl http2;

   ssl_certificate ...;
   ssl_certificate_key ...;

   return 301 https://www.example.com$request_uri;
}

server塊重定向所有進入http://example.comhttps://example.com到的請求https://www.example.com

http://www.example.com然後,和總共有兩個塊https://www.example.com

server {
   listen 80;

   server_name www.example.com;

   return 301 https://www.example.com$request_uri;
}

server {
   listen 443 ssl;

   server_name www.example.com;

   ssl_certificate ...;
   ssl_certificate_key ...;

   ... rest of config ...
}

引用自:https://serverfault.com/questions/982016