最近想把轻量服务丢在netcup 0.84EUR
上整个All in one
,也懒得域名解析那么多了。但单域名就会有个问题:指定多级目录的情况下,如果/abc
的网页服务请求/js
目录会报错,因为其请求的/js
目录不应该是域名下的/js
,而应该是请求/abc/js
目录。
但在网络上搜到的都是直接硬rewrite
,而我有多个多级目录,不可能这么做,所以就缝合了一个想法:
1. 先是和gpt对线,他给了一个给每个/abc目录产生的请求赋予/abc header的想法,认为能自动处理,实际不行;
2. 然后我去网上搜,发现了有通过if判断请求文件名来转发的方式
3. 产生了把上述方式合二为一的想法,即给每个/abc目录的请求赋予/abc header,然后通过判断/abc header进行转发
4. 测试下来思路可行
具体nginx demo
配置如下(demo
的二级目录为smokeping
):
location / {
# your main conf...
# judge header
if ($http_referer ~ /smokeping) {
# If the SmokePing header is set, rewrite accordingly
# Only rewrite css/js/cache path. You can structure your own configuration file based on your own needs.
rewrite ^/(css|js|cache)/(.*)$ /smokeping/$1/$2 last;
}
}
location /smokeping {
# This block is for requests specifically targeting /smokeping
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Adding header
proxy_set_header Referer /smokeping;
proxy_pass http://127.0.0.1:9008/;
}
如果是三级目录,则如下:
location / {
# Your own conf
}
location /smokeping {
if ($http_referer ~ "/smokeping/cc") {
# If the SmokePing header is set, rewrite accordingly
# Only rewrite css/js/cache path. You can structure your own configuration file based on your own needs.
rewrite ^/smokeping/(css|js|cache)/(.*)$ /smokeping/cc/$1/$2 last;
}
if ($http_referer ~ "/smokeping/netcup") {
# If the SmokePing header is set, rewrite accordingly
# Only rewrite css/js/cache path. You can structure your own configuration file based on your own needs.
rewrite ^/smokeping/(css|js|cache)/(.*)$ /smokeping/netcup/$1/$2 last;
}
location /smokeping/cc {
# This block is for requests specifically targeting /smokeping/cc
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Adding header
proxy_set_header Referer /smokeping/cc;
proxy_pass http://0.0.0.0:9008/;
}
location /smokeping/netcup {
# This block is for requests specifically targeting /smokeping/netcup
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Adding header
proxy_set_header Referer /smokeping/netcup;
proxy_pass http://0.0.0.0:49131/;
}
}
如果懒得判断需要转发哪些目录,想全部转发,则把rewrite
部分改为以下即可(作为参考,根据自己需求修改):
rewrite ^/(.*)$ /smokeping/$1 last;
未进行效率测试,但就我个人角度而言,私以为额外处理并检查请求中的 Referer
头这种微小的性能损失相比于使用 Nginx
来处理资源路径重写所提供的便利性而言是可以接受的
总结
nginx
转发配置本身不变,只是在每个对应目录下添加对应的Referer
头,再在上一级的配置中进行对Referer
头的判断并进行rewrite
。