【问题标题】:Nginx: rewrite for subdomain to folder AND files inside itNginx:将子域重写为其中的文件夹和文件
【发布时间】:2019-05-19 03:38:26
【问题描述】:

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

server {
listen      x.x.x.x:80;
server_name domain *.domain;

root /home/admin/web/domain/public_html/subs/$subdomain;    # here is IF for subdomains
set $subdomain "";
if ($host ~* ^([a-z0-9-\.]+)\.domain$) {
    set $subdomain $1;
}
if ($host ~* ^www.domain$) {
    set $subdomain "";
}


index       index.php;


location / {    # here is rules for ROOT domain

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

........

效果很好,但我有一个问题。

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

file(key.txt);

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

【问题讨论】:

  • rewrite $request_uri $subdomain.$request_uri; 不起作用

标签: php nginx subdomain rules


【解决方案1】:

您应该添加额外的位置来处理 php 文件。为了简化规则,我将根目录移动到 /tmp/subs/root 子目录。

server {
    listen 80;
    server_name domain.test *.domain.test;

    set $subdomain "root";
    if ($host ~* ^([a-z0-9-\.]+)\.domain.test$) {
        set $subdomain $1;
    }
    if ($host ~* ^www.domain.test$) {
        set $subdomain "root";
    }

    root /tmp/subs/$subdomain;

    location / {
        index    index.php;

         if (!-e $request_filename) {
             rewrite ^(.*)$ /index.php last;
             break;
         }
    }

    location ~ /(.+\.php) {
        index index.php;

        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  PATH_INFO        $fastcgi_script_name;
        include fastcgi_params;
    }
}

目录结构:

/tmp/subs/root/index.php
/tmp/subs/d1/index.php
/tmp/subs/d2/index.php
/tmp/subs/d2/key.txt

/tmp/subs/d2/index.php:

<?php
    $file = file('key.txt');
    print_r($file);

/tmp/subs/d2/key.txt

hello there

【讨论】:

  • 谢谢。这对我不起作用。根据您的解决方案,我已将所有文件移至/tmp/subs/,现在服务器返回File not found. 这是域的固定配置,您能看到吗? pastebin.com/9s40VDh3 。我也将其添加到第一篇文章中
  • @BenjaminColeman 似乎在配置中的某处添加了打破上述示例的新位置规则。要查找问题,只需将主要规则留在配置中,然后一一添加新的位置规则。
  • 工作正常。非常感谢
猜你喜欢
  • 2023-03-27
  • 2019-12-21
  • 2012-12-25
  • 2010-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
相关资源
最近更新 更多