我尝试使用 nginx 将任何到端口 80 和 8080 的内容重定向到 443 (https)。这是针对 Jenkins 服务器的。我使用的是 ubuntu。这是我目前的 nginx 配置:
server {
listen 80;
server_name jenkins.mydomain.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_redirect http://localhost:8080 https://jenkins.mydomain.com;
}
return 301 https://jenkins.mydomain.com$request_uri;
}
server {
listen [::]:443 ssl ipv6only=on;
listen 443 ssl;
server_name jenkins.mydomain.com;
ssl on;
ssl_certificate /path/to/wildcard.mydomain.com.crt;
ssl_certificate_key /path/to/wildcard.mydomain.com.key;
location / {
add_header Cache-Control private;
expires epoch;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header Host $host;
proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
proxy_ssl_server_name on;
include /etc/nginx/proxy_params;
proxy_pass http://localhost:8080;
proxy_read_timeout 90s;
proxy_redirect http://localhost:8080 https://jenkins.mydomain.com;
}
}
如您所见,我尝试将代理相关标头添加到端口 80 服务器块,但不起作用。当我转到http://jenkins.mydomain.com或者http://jenkins.mydomain.com:8080它不会重定向到https://jenkins.mydomain.com。如何将任何发送到端口 80 和 8080 的内容重定向到 443?
答案1
我正在使用此配置,可能来自任何文档页面,并且它已经运行多年,没有任何问题。它可能应该更好,但对于我的内部使用来说已经足够了。
upstream jenkins {
server 127.0.0.1:8080 fail_timeout=0;
}
server {
listen 80;
listen [::]:80;
server_name XXXX fail_timeout=0;
return 301 https://XXXXX$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
ssl on;
ssl_certificate /etc/nginx/ssl/XXXX.cert.pem;
ssl_certificate_key /etc/nginx/ssl/XXXX.key.pem;
server_name XXXXX;
location / {
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://jenkins;
proxy_redirect http:// https://;
add_header Pragma "no-cache";
}
}