【发布时间】:2016-01-09 02:29:32
【问题描述】:
我有几个关于我的 nginx 配置的问题,因为它与提供 webp 文件以及使用带有 try_files 的命名位置有关。
当前配置:
server {
listen 80;
server_name assets.manager manager;
passenger_app_env production;
passenger_ruby /home/web-server/.rvm/gems/ruby-2.2.1@manager/wrappers/ruby;
passenger_enabled on;
error_log /home/web-server/web-applications/manager/current/log/nginx-error.log;
root /home/web-server/web-applications/manager/current/public;
satisfy any;
allow 127.0.0.1;
allow 192.168.0.0/24;
deny all;
location ~ ^/assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
add_header Last-Modified "";
add_header ETag "";
}
location ~* .+\.(?:png|jpe?g|gif)$ {
if ($webp_suffix != "") {
add_header Vary Accept;
}
try_files $uri$webp_suffix $uri =404;
}
}
就目前而言,nginx 不提供 webp 文件。如果我将add_header X-Webp-Uri "$uri$webp_suffix"; 放在第一个location 块内,则会添加标题。如果我将它放在与location 块匹配的第二个 png/jpeg 中,则不会设置标题。据我了解,正则表达式位置块是连续的(即,它不会在第一次匹配时停止匹配)。
1) 我想提供 webp 图像(如果存在)(我的尝试是第二个 location 块)。在这种情况下,嵌套的 location 块会有所帮助吗?我想为 /assets/ 中的所有文件设置 gzip_static、expires 等,但我只想为 /assets/ 中的某些文件扩展名提供 webp 版本。
2) 在另一个主题上,我想提供静态 .html 文件(如果存在)。为此(在网上查找教程后),我需要try_files 和指向上游应用程序(Rails)的命名位置块的组合。但是,如果我使用Passenger(使用passenger-install-nginx-module 安装),我似乎不知道如何声明上游块。对于Passenger/Nginx 设置,我能找到的唯一配置是使用passenger_enabled on;
编辑:我找到了一个示例配置;这是一个例子(这忽略了问题 #1):
server {
listen 80;
server_name assets.staging.pos staging.pos;
passenger_app_env staging;
passenger_ruby /home/vagrant/.rvm/gems/ruby-2.2.1@pos/wrappers/ruby;
passenger_enabled on;
error_log /home/vagrant/rails/staging.pos/log/nginx-error.log;
root /home/vagrant/rails/staging.pos/public;
try_files $uri /cache/$uri /cache/$uri.html @app;
location @app {
proxy_set_header X-Forwarded-Proto http;
}
location ~* ^/images/.+\.(png|jpe?g)$ {
if ($webp_suffix != "") {
add_header Vary Accept;
}
try_files $uri$webp_suffix $uri =404;
}
}
编辑 2:我发现 nginx 完全清除了 if 块之外的任何指令!
这将导致仅设置 Vary Accept 标头:
server {
location ~* ^/images/.+\.(png|jpe?g)$ {
add_header X-Whatever "Yo";
if ($webp_suffix != "") {
add_header Vary Accept;
}
}
}
这将导致设置两个标题:
server {
location ~* ^/images/.+\.(png|jpe?g)$ {
if ($webp_suffix != "") {
add_header Vary Accept;
add_header X-Whatever "Yo";
}
}
}
编辑 3:所以现在它更加令人困惑。就像之前的任何 add_header 不在最后一个代码块(位置或 if 语句)中一样,都将被完全忽略。即,使用以下内容,仅设置 X-Whatever 标头:
location ~ ^/assets/ {
gzip_static on;
expires max;
add_header Cache-Control public; # Ignored?!
add_header Last-Modified ""; # Ignored?!
add_header ETag ""; # Ignored?!
location ~* ^/assets/.+\.(?:png|gif|jpe?g)$ {
add_header X-Something "$uri$webp_suffix"; # Not ignored!
}
}
【问题讨论】:
标签: ruby-on-rails regex nginx passenger webp