我试图在Ubuntu的Ngnix后面设置Angular + Nodejs。
对于Angular和Nodejs API,一切都很好,但我无法提供静态文件。
下面是我的配置(/etc/nginx/sites-enabled/default):
location / {
# First attempt to serve request as file, then as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://localhost:7777;
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;
# preflight requests
if ( $request_method = OPTIONS ) {
add_header "Access-Control-Allow-Origin" *;
add_header "Access-Control-Allow-Credentials" true;
add_header "Access-Control-Allow-Methods" "GET, POST, PUT, HEAD, DELETE, OPTIONS";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
return 200;
}
}
location /static {
proxy_pass http://localhost:7777;
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;
}
/api路由可以正常工作,但是/static不能。
在本地,/static工作良好,因为没有nginx。
我有以下目录结构来提供静态文件:
public
static
images
css
fonts
https://somewebsite.com/api/read(工作正常)
https://localhost:3000/static/images/test.png(工作正常)
https://somewebsite.com/static/images/test.png
不能工作。我做错了什么?
https://localhost:3000/static/images/test.png (works fine)
和https://somewebsite.com/static/images/test.png
符合预期。根据您的配置,您还将/static
重定向到端口7777
:proxy_pass http://localhost:7777;
改变:proxy_pass http://localhost:7777;
:proxy_pass http://localhost:3000;
应该会有效果
我用下面的条目修复了这个问题:
location /static/ {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_pass "http://localhost:7777/static/";
# preflight requests
if ( $request_method = OPTIONS ) {
add_header "Access-Control-Allow-Origin" *;
add_header "Access-Control-Allow-Credentials" true;
add_header "Access-Control-Allow-Methods" "GET, POST, PUT, HEAD, DELETE, OPTIONS";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
return 200;
}
}