大网数据广告活动
服务器运维问答

Serving a static file for a certain user agent

· 52CE 我爱测

I have the following config: server { listen 80; listen [::]:80; server_name example.com; return 302 https://$server_name$request_uri; } server { # SSL configuration listen 443 ssl http2; listen [::]:443 ssl http2; ssl on; ssl_ce…

问题原文

原帖链接 · DrDinosaur · CC BY-SA 4.0

I have the following config:

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    return 302 https://$server_name$request_uri;
}

server {

    # SSL configuration

    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    ssl        on;
    ssl_certificate         /etc/ssl/certs/cert.pem;
    ssl_certificate_key     /etc/ssl/private/cert.pem;

    server_name example.com;

    root /var/www/example;
    index index.html;


    location / {
            if ( $http_user_agent = "Dinosaur" ) {
                rewrite https://example.com/ https://example.com/example.gif;
            }
            try_files $uri $uri/ =404;
    }
}

In a request to the root of https://example.com, I want the index.html to be served. However, if the request is made with a special user agent, then I want it to serve the example.gif file directly (not 301 or 302 redirecting to the https://example.com/example.gif URL).

How can I do this? The rewrite doesn't appear to be working. The try_files directive doesn't work in an if context, which may or may not be necessary to check for the user agent condition.

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

The correct location statement for the root of https://example.com is location = /. The location / statement matches any URI that is not handled by some other location block. See this document for details.

Your rewrite statement is completely wrong. See this document for details.

Testing the value of the $http_user_agent is accomplished with an if block. You may want to use ~ instead of =, if the value contains "Dinosaur" rather than being an exact match. Also, statements within the if block should be limited to rewrite...last and return. See this document for details.

location / {
    try_files $uri $uri/ =404;
}
location = / {
    if ( $http_user_agent ~ "Dinosaur" ) {
        rewrite ^ /example.gif last;
    }
}

If the if block is not taken, the default action is to process the index statement and serve the index.html file.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-01-06)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。