我在几乎所有通过 nginx 代理转发的 nodejs 应用中都有类似的项目结构和目录。结构如下:
/var/srv
-/app1
-/public
-/css
-/js
-/img
-/app2
-/public
-/css
-/js
-/img
-/app3
-/public
......
希望您能理解。目前,我已经通过为每个项目提供位置和别名,在 nginx 中对提供静态文件的代码进行了硬编码,但我想要的是这样的:
location /$app_var/public/(js or css or img or other static content) {
然后将其别名为
alias /var/srv/$app_var/public/(js or css or img or other static content)
这样它就可以根据项目的目录提供静态内容,而我不必手动指定每个项目位置。如果我没有更好地解释,请发表评论。谢谢 :)
我当前的配置:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /srv/www/;
index index.html index.htm;
server_name example.com www.example.com;
rewrite ^/(.*) https://nulll.me/$1 permanent;
}
server {
listen 443;
server_name example.com example.com;
root /srv/www/;
index index.html index.htm;
ssl on;
ssl_certificate /home/---------------.crt;
ssl_certificate_key /home/------------.key;
ssl_session_timeout 5m;
ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers AES256+EECDH:AES256+EDH:!aNULL;
location / {
try_files $uri $uri/ =404;
}
location /app1 {
alias /srv/www/watch/;
proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
#simillarly more apps
location /app1/public/img {
alias /srv/www/app1/img/;
access_log off;
expires max;
}
# simillarly for /css , /js and for each website.
}
答案1
使用正则表达式?
类似这样的事情应该可以实现:
location ~ ^/(?<app>[^/]+)/public/(?<dir>[^/]+)/(?<file>[^/]+)$ {
alias /var/srv/$app/public/$dir/$file;
}