![在同一个 nginx 服务器下定义两个监听(80 和 443)是否正确?](https://linux22.com/image/742337/%E5%9C%A8%E5%90%8C%E4%B8%80%E4%B8%AA%20nginx%20%E6%9C%8D%E5%8A%A1%E5%99%A8%E4%B8%8B%E5%AE%9A%E4%B9%89%E4%B8%A4%E4%B8%AA%E7%9B%91%E5%90%AC%EF%BC%8880%20%E5%92%8C%20443%EF%BC%89%E6%98%AF%E5%90%A6%E6%AD%A3%E7%A1%AE%EF%BC%9F.png)
定义两者是否正确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;
}
答案1
据我所记得,是的。文档中也这么说(下面的链接):
单个 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
答案2
允许在同一个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.com
或的请求重定向https://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 ...
}