如何在保留静态资源的相关URL的同时设置NGINX反向代理?

我试图在NGINX中使用proxy_pass设置一个反向代理。 页面加载正常,但所有使用相对URL的静态辅助(js,css,imgs)都会因为它预先安装父服务器的主机名而中断。 有没有办法使用反向代理,同时维护所有静态资源的代理主机名?

parent.conf

server { listen 80; server_name parent.mydomain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name parent.mydomain.com; root /var/www/parent; index index.html; try_files $uri.html $uri $uri/ =404; # error and access out error_log /var/log/error.log; access_log /var/log/access.log; ssl on; ssl_certificate /etc/ssl/myssl.pem; ssl_certificate_key /etc/ssl/myssl-key.pem; # Here is the important part. Any url matching # this pattern needs to proxy_pass to child. location ~ "^/[a-z0-9]{24}$" { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass https://child.mydomain.com; proxy_redirect off; } } 

child.conf

 server { listen 80; server_name child.mydomain.com; return 301 https://$server_name$request_uri; } server { listen 443; server_name child.mydomain.com; root /var/www/child; ssl on; ssl_certificate /etc/ssl/myssl.pem; ssl_certificate_key /etc/ssl/myssl-key.pem; error_log /var/log/child.log; access_log /var/log/child.log; # this is a single page app so all request # should be routed through index.html. location / { try_files $uri /index.html; } } 

现在如果我打https://parent.mydomain.com/54570f77968d6e492b0d68afchild.mydomain.com索引页加载好,但没有我的静态文件做,因为他们正试图加载在https://parent.mydomain.com而不是他们实际位于https://child.mydomain.com/js/main.js

而不是反向代理“ip”地址(proxy_pass http://127.0.0.1:9003 ),请尝试proxy_pass http:// YourHostNameBehindReverseProxy:9003 。

然后将YourHostNameBehindReverseProxy添加到/ etc / hosts并与127.0.0.1关联。

@cnst我不希望父母加载除索引页面以外的任何东西。 我需要主机的所有静态资源保持child.mydomain.com – jwerre 7分钟前

那么你的问题似乎是serverfault offtelic,然后。

那么最好的方法就是使用<base href='https://child.mydomain.com/'/>来确保浏览器始终从child.mydomain.com加载所有资源:

 <html> <head> <base href='https://child.mydomain.com/'/> 

或者,如果您在父母本身中没有其他任何您想要提供的服务,那么您可以简单地执行从所有404页面向该子页面的301 Movedredirect。

  error_page 404 =301 http://child.mydomain.com$request_uri; 

或者,更好的是,从父级删除您的try_files ,而是将所有不匹配更具体位置的请求redirect到子级:

 location / { return 301 http://child.mydomain.com$request_uri; }