我有一个带有nginx的vhost:
- 如果是静态文件,请将其发送到Apache
-
如果是python文件,请将其发送到Python Weberver
server { listen *:80; server_name mywebsite.fr; index index.html index.htm; access_log /var/log/nginx/proxy-access-mywebsite.log proxylog; error_log /var/log/nginx/proxy-error-mywebsite.log error; # vhost for static files location ~ ^/(static|public)/.* { 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-Server $host; proxy_pass http://apache$uri; } location / { 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-Server $host; proxy_pass http://mywebsite/; } }
在我的apache中,我有这些重写规则:
RewriteEngine On
# Remove all /
RewriteRule ^/static/CACHE/(.*) static/CACHE/$1
RewriteRule ^/static/(.*) static/production/$1
RewriteRule ^/public/(.*) uploads/$1
# If file, stop
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule . - [QSA,L]
# Let's try with full path, if file then rewrite + stop:
RewriteCond %{DOCUMENT_ROOT}/$1 -f
RewriteRule (.*) %{DOCUMENT_ROOT}/$1 [QSA,L]
RewriteCond %{DOCUMENT_ROOT}/production/$1 -f
RewriteRule (.*) %{DOCUMENT_ROOT}/production/$1 [QSA,L]
,但我只是意识到传递给Apache很愚蠢:Nginx可以充当静态文件的缓存!
我想为NGINX服务器重写这些规则,但到目前为止都没有任何可行的规则。我认为我的最大问题是测试它是否是带有完整路径的文件,如果是的,请用作缓存服务器并立即将其发送回。
您将如何将8行Apache重写为Nginx的规则?
您是否尝试过像bellow这样的规则?
# nginx configuration
location /static {
rewrite ^/static/CACHE/(.*) /static/CACHE/$1;
rewrite ^/static/(.*) /static/production/$1;
}
location /public {
rewrite ^/public/(.*) /uploads/$1;
}
location / {
rewrite ^(.*)$ /$document_root/$1 break;
rewrite ^(.*)$ /$document_root/production/$1 break;
}
您必须尝试不同的组合,因为nginx规则可能很棘手,而在不实际测试规则的情况下,很难转换它们并实际使用第一次尝试。
设置日志路径/文件
error_log /var/log/nginx/error.log notice;
INSIDE OF HTTP SCOPE ADD ->
http {
rewrite_log on;
这是我的工作配置
upstream mywebsite {
ip_hash;
server 127.0.0.1:8006;
}
server {
listen *:80;
server_name mywebsite.com www.mywebsite.com;
index index.html index.htm;
access_log /var/log/nginx/proxy-access-mywebsite.log proxylog;
error_log /var/log/nginx/proxy-error-mywebsite.log error;
# ~ = regular expression
# ~* = regular expression case *insensitive*
location ~* ^/static/(?<p>.+) {
root /web/htdocs/mywebsite/htdocs/static;
try_files /$p /production/$p =403;
access_log off;
expires 1h;
}
location ~* ^/public/(?<p>.+) {
root /web/htdocs/mywebsite/htdocs/uploads;
try_files /$p =403;
access_log off;
expires 1h;
}
location / {
expires -1;
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-Server $host;
proxy_pass http://mywebsite/;
}
}