我建立了一个使用 Rest API 获取所有数据的网站。我的网站使用 SSL 证书进行保护。我的默认文件 (etc/nginx/sites-enabled/default
) 如下所示:
server {
listen 80;
server_name example.com;
rewrite ^/(.*) https://example.com/$1 permanent;
}
server {
listen 443 ssl;
listen [::]:80 default_server;
root /var/www/example;
index index.html;
server_name example.com;
ssl_certificate /root/example.com.crt;
ssl_certificate_key /root/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
try_files $uri $uri/ =404;
}
}
问题是我的 Rest API(我从中获取所有数据)还必须具有 SSL 证书才能将所有数据安全地传输到我的网站。
我在默认文件 (etc/nginx/sites-enabled/default
) 中为其余 api 创建了另一个服务器 block 。它看起来像这样:
server {
listen 8877;
server_name example.com;
rewrite ^/(.*) https://example.com:8877/$1 permanent;
}
server {
listen 443 ssl;
listen [::]:8877 default_server;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name example.com;
ssl_certificate /root/example.com.crt;
ssl_certificate_key /root/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
proxy_pass http://example.com:1111;
}
}
我知道我应该像这样组合它们:
server {
listen 80ssl;
listen 8877 ssl;
index index.html index.htm index.nginx-debian.html;
server_name example.com;
ssl_certificate /root/example.com.crt;
ssl_certificate_key /root/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
// DO SOMETHING
}
}
问题是我需要 location block 在端口 80 和端口 8877 上以不同方式运行。在端口 8877 上,location block 应该指向我在后台运行的 NodeJS 项目 proxy_pass http://example.com:1111;
。在端口 80 上,它不应指向我的 NodeJS 项目。我怎样才能做到这一点?
或者有更好的方法来实现这个目标吗?我已经被这个问题困扰了 2 天。购买第二个域或 SSL 证书不是一种选择 + 我的证书支持单个域上的多个端口。
最佳答案
这是我会做/尝试的:
(如果不需要,您应该考虑关闭 TLS 1.0)
# General HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name example.com default_server;
location / {
return 302 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name example.com default_server;
root /var/www/example;
index index.html;
ssl_certificate /root/example.com.crt;
ssl_certificate_key /root/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 8877 ssl;
listen [::]:8877 ssl;
server_name example.com;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
ssl_certificate /root/example.com.crt;
ssl_certificate_key /root/example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location / {
proxy_pass http://example.com:1111;
}
}
关于node.js - NGINX:使用 1 个域名为多个端口设置 SSL 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50591202/