简体   繁体   中英

How To Set Up common one Nginx Server Blocks (Virtual Hosts) for all peojects in Centos

I have a Centos with Nginx server and multiple site folders are exist in wamp.

But for every project i should need to write separate Nginx server blocks under /etc/nginx/conf.d/websites.conf file. So whenever i created a new project then after i have to add below lines under websites.conf file of Nginx.

location /project-folder {
        root path;
        index index.php index.html index.htm;
        rewrite ^/project-folder/(.*)$ /project-folder/app/webroot/$1 break;
        try_files $uri $uri/ /project-folder/app/webroot/index.php?q=$uri&$args;

        location ~ .*\.php$ {
            include /etc/nginx/fastcgi_params;
            fastcgi_pass 127.0.0.1:xxxx;
            fastcgi_index index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        }
        location ~* /project-folder/(.*)\.(css|js|ico|gif|png|jpg|jpeg)$ {
            root path/project-folder/app/webroot/;
            try_files /$1.$2 =404;
        }

    }

So is it any other way to make a common block for all site-folder and doesn't need to add new server block for new site?

Thanks in advance.

There are multiple ways to implement this. If you are using multiple domain names, you can use a regular expression in the server_name to create named captures (see this document for more). You can use a regular expression in the location directive to capture the value of project-folder (see this document for more).

The main function of this configuration is to insert the text /app/webroot between the project name and the remainder of the URI. The challenge is to do it without creating a redirection loop.

I have tested the following example, which works by placing a generalised version of your rewrite statement into the server block and capturing the project name for use later in the one of the try_files statements:

server {
    ...

    root /path;
    index index.php index.html index.htm;

    rewrite ^(?<project>/[^/]+)(/.*)$ $1/app/webroot$2;

    location / {
        try_files $uri $uri/ $project/index.php?q=$uri&$args;
    }
    location ~ .*\.php$ {
        include /etc/nginx/fastcgi_params;
        fastcgi_pass 127.0.0.1:xxxx;
        fastcgi_param  SCRIPT_FILENAME $request_filename;
    }
    location ~* \.(css|js|ico|gif|png|jpg|jpeg)$ {
        try_files $uri =404;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM