我目前正在尝试使用Nginx设置React Apps的多个项目。到目前为止,每当我有静态文件冲突时,我只是将所有内容从一个文件夹复制到另一个文件夹(是的,这是一个糟糕的解决方案,但到目前为止它是有效的)。问题是,现在我在同一台服务器上有多个项目,虽然以前的解决方案仍然有效,但用不了多久,它就会变得一团糟。我已经查找了Stack Overflow和许多网站,我找到了一个看起来像我想要做的配置,但它不能正常工作。
这是我的nginx.conf文件:
#user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
server_names_hash_bucket_size 64;
#gzip on;
index index.html index.htm;
map $http_referer $webroot {
"/project1/main" "/home/username/project1main/build";
"/project1/admin" "/home/username/project1admin/build";
"/project2/main" "/home/username/project2main/build";
"/project2/admin" "/home/username/project2admin/build";
}
include /etc/nginx/conf.d/*.conf;
}这是我的server.conf文件:
server {
listen 80;
server_name gcloud-server;
location /project1/main {
alias /home/username/project1main/build;
try_files $uri $uri/ /index.html =404;
}
location /project1/admin {
alias /home/username/project1admin/build;
try_files $uri $uri/ /index.html =404;
}
location /project2/main {
alias /home/username/project2main/build;
try_files $uri $uri/ /index.html =404;
}
location /project2/admin {
alias /home/username/project2admin/build;
try_files $uri $uri/ /index.html =404;
}
location /static {
root $webroot;
}
}有没有办法像这样解决这个问题?或者我不得不设置一个/static位置,在这个位置我必须复制每个项目的静态文件?
提前谢谢。
发布于 2020-06-10 23:49:02
据我所知,alias指令是如何工作的,您遇到了以下问题。假设您收到了一个/project1/main/some/path/file请求:
location /project1/main {
alias /home/username/project1main/build;
# here our internal variables are:
# $document_root = "/home/username/project1main/build"
# $uri = "/project1/main/some/path/file"
try_files $uri $uri/ /index.html =404;
# 1) try_files checks the existence of $document_root$uri physical file
# this is "/home/username/project1main/build/project1/main/some/path/file"
# which is absent
# 2) try_files checks the existence of $document_root$uri/ directory
# this is "/home/username/project1main/build/project1/main/some/path/file/"
# which is absent
# 3) you've got a 404 HTTP error
}在使用root指令时不会出现这个问题,但是alias是这样工作的。你能做的是
# use regex location match and capture URI suffix in a $1 variable
location ~ /project1/main(.*) {
alias /home/username/project1main/build;
# here our internal variables are:
# $document_root = "/home/username/project1main/build"
# $uri = "/project1/main/some/path/file"
# $1 = "/some/path/file"
try_files $1 $1/index.html =404;
# checked file is $document_root$1
# this is "/home/username/project1main/build/some/path/file"
# request would be served if this file exists
}https://stackoverflow.com/questions/62307347
复制相似问题