Home > OS >  How can I put multiple paths into the same domain in nginx?
How can I put multiple paths into the same domain in nginx?

Time:02-15

I want to connect domain.com/c to /var/www/a/c and domain.com/b to /var/www/b. And I wrote nginx sites-available file like following:

server {
    listen 443 ...

    index index.php index.html;
    server_name domain.com;
    root /var/www/a;

    location / {
        try_files $uri $uri/ =404;
    }

    location /b {
        root /var/www/b;
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.0-fpm.sock;
    }
}

But I see 404 when I enter domain.com/b. I tried using alias instead of root but I got the same result. How can I do?

CodePudding user response:

It is because your location ~ \.php$ { ... } uses your global root /var/www/a;. Here are just two possible solution among many others:

  1. Use the nested PHP handler:

    server {
        listen 443 ...
    
        index index.php index.html;
        server_name domain.com;
        root /var/www/a;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location ^~ /b/ {
            root /var/www;
            try_files $uri $uri/ /b/index.php?$query_string;
            location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/run/php/php8.0-fpm.sock;
            }
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        }
    }
    

    Or if your /var/www/b is the only PHP app, your can just add a root directive to your PHP handler:

    server {
        listen 443 ...
    
        index index.php index.html;
        server_name domain.com;
        root /var/www/a;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location /b/ {
            root /var/www;
            try_files $uri $uri/ /b/index.php?$query_string;
        }
    
        location ~ \.php$ {
            root /var/www;
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        }
    }
    
  2. Use the map directive to get your web root from the request URI:

    map $uri $root {
        ~^/b/    /var/www;
        default  /war/www/a;
    }
    server {
        listen 443 ...
    
        index index.php index.html;
        server_name domain.com;
        root $root;
    
        location / {
            try_files $uri $uri/ =404;
        }
    
        location /b/ {
            try_files $uri $uri/ /b/index.php?$query_string;
        }
    
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.0-fpm.sock;
        }
    }
    
  • Related