
我的開發情況是,我有一個包含多種服務的網域:
https://somewebpage.com
在此服務上有多個項目作為子目錄
https://somewebpage.com
<- 登陸頁面https://somewebpage.com/api
<- 休息 API 伺服器https://somewebpage.com/app
<- 我的應用程式
那麼是否可以(以及如何)設定 nginx 和主機檔案以僅反向代理https://somewebpage.com/app
到我的本機建置http://localhost:3000
?
/api
問題是,當部署應用程式時,訪問其餘伺服器沒有問題,但在本地提供服務時,我的 nginx 反向代理也會攔截landing page
和rest api server
url。
我的 nginx 設定如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
index index.html;
proxy_max_temp_file_size 0;
proxy_buffering off;
server {
listen 80;
server_name somewebpage.com;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name somewebpage.com;
ssl_certificate /etc/ssl/certs/certificate.crt;
ssl_certificate_key /etc/ssl/certs/ccertificate.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location /app {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_pass http://localhost:3000;
}
}
}
在我的/etc/hosts
我有:
127.0.0.1 somewebpage.com
有其他技巧可以達到類似的結果嗎?
我嘗試這樣做的原因是,如果我從我的系統中執行此操作,localhost:3000
它會響應CORS
錯誤並拒絕我對 的調用/api
。
或者這是否存在太大的安全隱患,我必須要求其他訪問方式/api
?
感謝您提前的答覆。
答案1
您需要添加以下內容:
location / {
try_files $uri $uri/ =404;
}
這告訴 nginx 如何處理與其他指定不符的請求location
。有關 nginx 如何選擇location
要使用的區塊的更多信息,請閱讀Nginx 文檔。
答案2
我想出了一個適合我的解決方案。
somewebpage.com
指向xx.xx.xx.xx
靜態 IP 位址,因此我只是添加了另一個轉發到該 IP 位址的代理,而不是類似於 Tero Kilkanen 答案的 URL。
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_pass https://xx.xx.xx.xx;
}
這樣/etc/hosts
文件就不會攔截我的somewebpage.com
請求,因為請求將繞過網域解析。
所以最後我得到了以下對我有用的 nginx 設定:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
index index.html;
proxy_max_temp_file_size 0;
proxy_buffering off;
server {
listen 80;
server_name somewebpage.com;
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name somewebpage.com;
ssl_certificate /etc/ssl/certs/certificate.crt;
ssl_certificate_key /etc/ssl/certs/ccertificate.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
location /app {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_pass http://localhost:3000;
}
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_pass https://xx.xx.xx.xx;
}
}
}
由於場景背後有多個 IP 位址或動態 IP 位址或其他原因,此解決方案可能不適合所有人。但它對我有用,並且對於開發目的來說已經足夠好了。