我在 Angular 中有一个支持 https 的前端,而在端口 10080 处有一个支持 http 的后端。我在 ngix 配置文件中尝试了几种反向代理方法,但仍然面临相同的问题。
当我尝试这种方法时,总是会出现错误“从来源‘https://example.com’访问‘https://example.com:30080/api/remoteControl/getactiveusers’的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在‘Access-Control-Allow-Origin’标头。”
server {
listen 443 ssl;
server_name _;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
root /usr/share/nginx/html;
index index.html index.htm;
include /etc/nginx/mime.types;
gzip on;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
ssl_certificate "xxx.crt";
ssl_certificate_key "xxx.key";
ssl_session_timeout 1d;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling off;
location / {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Content-Type text/plain;
add_header Content-Length 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' *;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
try_files $uri $uri/ /index.html;
}
location ~* \.(eot|ttf|woff|woff2)$ {
add_header Access-Control-Allow-Origin *;
}
}
server {
listen 10080 ssl http2;
server_name _;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
ssl_certificate "xxxx.crt";
ssl_certificate_key "xxx.key";
ssl_session_timeout 1d;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
ssl_session_cache shared:SSL:10m;
location / {
proxy_pass "http://backend:80" ;
proxy_set_header Connection Keep-alive;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
# proxy_set_header X-Forwarded-Host $host;
# proxy_hide_header X-Frame-Options;
proxy_buffers 4 256k;
proxy_buffer_size 128k;
proxy_busy_buffers_size 256k;
}
}
有人知道如何解决这个问题吗?
谢谢
答案1
您的设置存在多个问题。
首先,您有两个面向公众的 nginx 虚拟服务器,分别在端口 443 和端口 10080 上。您应该只有一个服务器监听端口 443 并从那里发出反向代理请求。
其次,您的后端正在生成包含类似 的链接的内容http://example.com:10080/page
。您的后端应该生成类似 的 URL https://example.com/page
。