你好,我当前的 nginx 配置对我来说运行良好,但我想确保对我的 API 的所有调用都是通过 https 进行的。我已经花了几个小时尝试这里发布的所有解决方案,但似乎我总是陷入重定向循环。
server {
listen 80 default_server;
listen [::]:80 default_server;
# SSL configuration
listen 443 ssl default_server;
ssl_certificate /etc/nginx/ssl/ssl-bundle.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
ssl_prefer_server_ciphers on;
index index.html index.htm index.nginx-debian.html;
server_name test.com;
location / {
root /var/www/html;
try_files $uri $uri/ @express;
}
location @express {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
我如何确保对 /api 的所有调用都仅通过 https?API 由 Express 提供。提前致谢。
答案1
您需要为 HTTP 和 HTTPS 设置单独的服务器块。
尝试一下这个 HTTP:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name test.com;
index index.html index.htm index.nginx-debian.html;
location /api {
redirect 301 https://$host$request_uri;
}
root /var/www/html;
}
它应该将所有调用重定向/api
至 http。
希望能帮助到你。
答案2
谢谢大家,我最终得到了这个令我高兴的配置,因为它将重定向到 https cpanel 部分以及 /api,并且主域可以使用 http 和 https。
server {
# SSL configuration
listen 443 ssl default_server;
ssl_certificate /etc/nginx/ssl/ssl-bundle.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
ssl_prefer_server_ciphers on;
index index.html index.htm index.nginx-debian.html;
location / {
root /var/www/html;
try_files $uri $uri/ @express;
}
location @express {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name example.com;
return 301 https://$host$request_uri;
}