Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: rewrite for subdomain to folder AND files inside it

I have nginx rewrite rule - it redirects all subdomain requests from sub to folder:

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;
    }

........

It work well, but i have one problem.

And in domain and subdomains i have a same php-script that gets data from txt file, like this:

file(key.txt);

My php-fpm module, i think, doesn't know about nginx rules and gets data in SUB from ROOT domain - it's wrong. Please help me to add nginx exceptions or add rule to get txt's data in SUB from SUBs. Not_from_root_domain. Thanks.

like image 250
Benjamin Coleman Avatar asked Jan 22 '26 18:01

Benjamin Coleman


1 Answers

You should add additional location to process php files. To simplify rules I moved root directory to /tmp/subs/root subdir.

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;
    }
}

dir structure:

/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
like image 104
Valery Viktorovsky Avatar answered Jan 25 '26 09:01

Valery Viktorovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!