首页 > 解决方案 > 根据主机重写 url

问题描述

我有一个服务于 Symfony 应用程序的 Nginx 服务器。但是这个应用程序可能会收到来自不同主机的请求(目前/etc/hostspublic

|-src
|-var
|-...
|-public
|   |-host1.com
|   |   |-file1
|   |   |-file2
|   |-host2.com
|   |   |-file1
|   |   |-...

URI 可以采用以下形式(请注意没有子目录名称):

https://host1.com/file1

在这种情况下,我希望 Nginx 检查是否public/host1.com/file1存在。所以我需要设置一种从/file1to的重写规则/host1.com/file1。如果文件存在,Nginx 必须提供它。但如果不是(即https://host1.com/file53),我希望 Nginx 重定向到 Symfony 应用程序,以便这个可以生成丢失的文件,并提供它。

我怎么能用 Nginx 做到这一点?

这是我的尝试。没有评论下方的 3 行,它作为经典服务器工作。

server {
    listen 80;
    root /var/www/project/public;

    location / {
        ##############################################
        # Here is my try, but Nginx crashes with this:
        ##############################################
        if ($host = "host1.com") {
            try_files /host1.com$uri /index.php$is_args$args;
        }

        try_files $uri /index.php$is_args$args;
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass myapp:9000;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
    }

    location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
        if (-f $request_filename) {
            expires 30d;
            access_log off;
        }
    }

    location ~ \.php$ {
        return 404;
    }

    rewrite_log on;
    error_log /var/log/nginx/project_error.log notice;
    access_log /var/log/nginx/project_access.log;
}

标签: nginxurl-rewriting

解决方案


正如评论中所建议的,使用不同server的块是解决方案。

我也遇到了以下部分的问题,它阻止了所有图像请求而不记录它,这在我的调试过程中造成了误解:

location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
    if (-f $request_filename) {
        expires 30d;
        access_log off;
    }
}

推荐阅读