我有一个应用程序,在一个端点上为后端(GraphQL API)和前端(VueJS SPA)提供服务:
/graphql
=> 后端端点(此处不需要进一步的路由)/
=> SPA(index.html,历史路由)SPA 正在使用历史路由。这意味着,视图是通过常见 URL 访问的,例如:
/login
/dashboard
该应用程序以及 nginx Web 服务器都在 Docker 容器中运行,并且可以相互访问。对于 nginx 服务器,我有以下配置:
server {
listen 4430 ssl;
server_name myapp.mydomain.ch;
ssl_certificate /etc/letsencrypt/live/myapp.mydomain.ch/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/myapp.mydomain.ch/privkey.pem;
location / {
proxy_pass http://myhost:10000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
try_files $uri $uri/ /index.html;
}
location /graphql {
proxy_pass http://myhost:10000/graphql;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
到目前为止效果很好。该应用程序可以在
myapp.mydomain.ch
使用。但是,如果我使用现有路由刷新页面或重定向到特定视图/路径,网络服务器将返回以下错误:
nginx | 2023/12/27 14:09:27 [error] 20#20: *6 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 81.62.132.74, server: myapp.mydomain.ch, request: "GET /favicon.ico HTTP/1.1", host: "myapp.mydomain.ch", referrer: "https://myapp.mydomain.ch/login"
据我了解,如果未找到路由,这应该始终返回index.html,这样就可以了,因为 SPA 可以处理路由。
我尝试通过多种方式更改 nginx 配置。示例:如果我使用以下配置:
location / {
proxy_pass http://myhost:10000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
该应用程序也运行良好。如果我刷新,我会收到 HTTP 404。这似乎符合逻辑,因为反向代理无法处理路由。
有谁知道我做错了什么或者 nginx 配置在我的设置中应该是什么样子?
这是我的设置。也许这里的一些东西可以帮助你
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/conf.d/certs/client/cert.pem;
ssl_certificate_key /etc/nginx/conf.d/certs/client/key.pem;
location / {
proxy_pass http://host.docker.internal:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /graphql {
proxy_pass http://host.docker.internal:4000;
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;
}
location ~ ^/graphql/ {
rewrite ^/graphql(.*) $1 break;
proxy_pass http://host.docker.internal:4000;
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;
}
}