我的架构设置是在 NodeJS 上的 CentOS 上运行的 SSO 服务,端口为 10102 和 10142,我需要将所有对端口 80 的请求在外部和内部重定向到 443,我将所有内容上游到 NodeJS 的上述端口,这是我的配置:
upstream sso1 {
server localhost:10102;
server localhost:10142;
}
server {
listen [::]:80;
listen 443 ssl;
server_name www.site.business site.business;
ssl_certificate /etc/nginx/cert.crt;
ssl_certificate_key /etc/nginx/cert.key;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
location / {
proxy_pass http://sso1;
proxy_read_timeout 90;
proxy_redirect http://sso1 https://www.site.business;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
但无论我做什么,该网站仍然可以通过 HTTP 和 HTTPS 访问。
知道为什么 Nginx 会忽略我吗?我实际上尝试了不同的配置,其中之一是捕获所有端口 80 请求并对其进行 301 重定向:
upstream sso1 {
server localhost:10102;
server localhost:10142;
}
server {
listen [::]:80;
server_name www.site.business site.business;
return 301 https://$server_name$request_uri;
}
server {
listen 443;
server_name www.site.business site.business;
ssl_certificate /etc/nginx/cert.crt;
ssl_certificate_key /etc/nginx/cert.key;
ssl on;
ssl_session_cache builtin:1000 shared:SSL:10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
ssl_prefer_server_ciphers on;
location / {
proxy_pass http://sso1;
proxy_read_timeout 90;
proxy_redirect http://sso1 https://www.site.business;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
答案1
在您的顶级配置中,您已告诉它监听 80 和 443。以下是针对您的情况的配置的重要部分,假设您希望网站仅在 www 子域上对 https 进行回复。
另一个关键是您可能必须为默认域设置一个监听器,该监听器为到达服务器的任何请求提供服务。
// Listen for requests for the main website
server {
server_name www.example.com;
listen 443 ssl http2; // https optional, need to build Nginx with correct module
ssl_certificatefullchain;
ssl_certificate_key privkey;
// locations etc
}
// Forward http requests for domain and www subdomain to main
server {
listen 80;
server_name example.com www.example.com;
return 301 https://www.example.com$request_uri;
}
// Forward https requests for root domain to main
server {
listen 443 ssl;
server_name example.com;
ssl_certificatefullchain;
ssl_certificate_key privkey;
return 301 https://www.example.com$request_uri;
}
我有这个配置来处理默认
# This just prevents Nginx picking a random default server if it doesn't know which server block to send a request to
server {
listen 80 default_server;
server_name _;
return 444; # This means "go away", effectively
}
我有一个很大的教程和示例配置文件可用这里。