nginx server configuration: subdomain to folder

独自空忆成欢 提交于 2019-12-02 20:45:41

As I found this Q&A on Google while looking for a solution for the same problem, I wanted to post the solution I finally used.


The first server block by MTeck looks pretty nice, but for the subdomains part you could simply do the following:

server {
  listen 80;
  server_name "~^(?<sub>.+)\.domain\.tld$";

  root /path/to/document/root/$sub;

  location / { try_files $uri $uri/ /index.php; }

  location ~ \.php {
    include fastcgi_params;
    fastcgi_pass  unix:/etc/nginx/sockets/domain.socket;
  }
}

This makes the root configuration directive dependent on the subdomain.

I spent hours beating my head against the wall and this is what works for me

server {
    listen       80;

    server_name ~^(?P<sub>.+)\.example\.com$; #<-- Note P before sub, it was critical for my nginx
    root /var/www/$sub; #<-- most important line cause it defines $document_root for SCRIPT_FILENAME

    location / {
            index index.php index.html; #<-- try_files didn't work as well
    }

    location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000; #<-- probably you have another option here e.g. fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
            include        fastcgi_params;
    }
}

You should take a look at http://wiki.nginx.org/IfIsEvil. You're doing a whole lot wrong in this configuration file.

server {
    server_name domain.tld www.domain.tld;

    location / {
        try_files $uri /index.php;
    }

    location ~ \.php {
        include fastcgi_params;
        fastcgi_pass  unix:/etc/nginx/sockets/domain.socket;
    }
}

server {
    server_name "~^(?<sub>.+)*\.(?<domain>.*)$";
    return 301 $scheme://$domain/$sub$request_uri;
}

If what you want is to keep that internal, you won't be able to rewrite it. By definition, a cross site rewrite needs to be sent back to the browser. You'll have to proxy the request.

server {
    server_name "~^(?<sub>.+)*\.(?<domain>.*)$";
    proxy_pass http://$domain/$sub$request_uri;
}

You should read the Nginx wiki. All of this is explained in depth.

This will work for www also.

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    index index.php index.html index.htm index.nginx-debian.html;
    server_name ~^www\.(?P<sub>.+)\.domain\.com$ ~^(?P<sub>.+)\.domain\.com$;
    root /var/www/html/$sub;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!