Nginx:将子域名重写到文件夹及其内部的文件

Nginx:将子域名重写到文件夹及其内部的文件

我有 nginx 重写规则 - 它将所有子域请求从子域重定向到文件夹:

server {
listen      77.77.77.77:80;
server_name domaincom *.domaincom;

root /home/admin/web/domaincom/public_html/subs/$subdomain;
set $subdomain "";
if ($host ~* ^([a-z0-9-\.]+)\.domaincom$) {
    set $subdomain $1;
    #rewrite $request_uri $1.$request_uri;
    #rewrite ^(.*txt)$ $subdomain.$request_uri;   just testing here
#rewrite ^(.*\.txt)$ $subdomain.$request_uri/$1;

}
if ($host ~* ^www.domaincom$) {
    set $subdomain "";
}

 # location $subdomain {
    # # # An example rewrite
    # rewrite ^/(.*txt)$ $request_uri;
# }

index       index.php;
access_log  off;
error_log /dev/null;


location / {

root        /home/admin/web/domaincom/public_html;
    location ~* ^.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
        expires     max;
    }

    location ~ [^/]\.php(/|$) {
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        if (!-f $document_root$fastcgi_script_name) {
            return  404;
        }

        fastcgi_pass    127.0.0.1:9002;
        fastcgi_index   index.php;
        include         /etc/nginx/fastcgi_params;
    }
}

error_page  403 /error/404.html;
error_page 404 = @foobar;

location @foobar {
return 301 /;
}
error_page  500 502 503 504 /error/50x.html;

location /error/ {
    alias   /home/admin/web/domaincom/document_errors/;
}

                # Access deny for bots
# See bots list in the /etc/nginx/nginx.conf
if ($limit_bots = 1) {
          return 403;
    }


location ~* "/\.(htaccess|htpasswd)$" {
    deny    all;
    return  404;
}

location /vstats/ {
    alias   /home/admin/web/domaincom/stats/;
    include /home/admin/conf/web/domaincom.auth*;
}

include     /etc/nginx/conf.d/phpmyadmin.inc*;
include     /etc/nginx/conf.d/phppgadmin.inc*;
include     /etc/nginx/conf.d/webmail.inc*;

include     /home/admin/conf/web/nginx.domaincom.conf*;
}

它运行良好,但我有一个问题。

在域和子域中我有一个相同的 php 脚本,可以从 txt 文件获取数据,如下所示:

file(key.txt);

我认为我的 php-fpm 模块不了解 nginx 规则,并从 ROOT 域获取 SUB 中的数据 - 这是错误的。请帮助我添加 nginx 例外或添加规则以从 SUB 获取 SUB 中的 txt 数据。Not_from_root_domain。谢谢。

答案1

对配置进行一些优化:

1)在指令的帮助下定义子域根目录map

map $http_host $root_suffix {
    ~^(?:www\.)?domain\.com$ "";
    ~^(.+)\.domain\.com$ /subs/$1;
}

2)根据请求URI后缀定义过期时间:

map $uri $expires {
    default off;
    ~*.+\.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ max;
}

(此map指令必须定义外部server { }在上下文级别上,块http { }

现在你的server { }区块:

server {
    listen      77.77.77.77:80;
    server_name .domaincom;
    root        /home/admin/web/domaincom/public_html$root_suffix;
    expires     $expires;

    index       index.php;
    access_log  off;
    error_log   /dev/null;

    # your locations here
    location ~ [^/]\.php(/|$) {
        ...
    }
    ...

相关内容