同网站不同 root

Ubuntu Nginx 同网站不同 root 常用指令

Nginx Multiple Root 同网站不同 Root

在做网站改版的时候,可能因为专案太大而无法一次全部改版,所以希望能够针对部分的 页面或API 进行改版,然后慢慢的全部迭代改版完成,为了做到这样的效果,可以透过 Nginx 指定不同的网址路径,去执行不同的程式,这边以 PHP Laravel Framework 为例。

由于旧专案是 Laravel 4.2 但新专案是 Laravel 5.5,程式改版过程中将改版完成的网址路径导向至 Laravel 5.5,但尚未完成改版的项目则还是继续导向至 Laravel 4.2,由 nginx 判断请求路径,去控制判断要执行哪一部分的程式。

server {
    listen 80;
    server_name _;
    # 预设使用 Laravel 5.5
    root "/home/deploy/laravel55/public";
    charset utf-8;
    index index.htm index.html index.php;
    error_page 404 /404.html;


    if ($request_uri ~* "^(.*/)index\.php/*(.*)") {
        return 301 $1$2;
    }

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

    location /elb-status {
        access_log off;
        return 200;
    }

    access_log /var/log/nginx/web-access.log cloudflare;
    error_log  /var/log/nginx/web-error.log error;
    location = /robots.txt { access_log off; log_not_found off; }
    location = /favicon.ico { access_log off; log_not_found off; }

    location ~ ^/assets/ {
        try_files $uri $uri/ /index.php?$args;
        expires max;
        add_header Cache-Control public;
        access_log off;
    }


    location ~ ^/(api|old-uri-path1|old-uri-path2)(.*)$ {
        # 指定旧网址,变更网站路径为 Laravel 4
        root "/home/deploy/laravel4/current/public";

        # Rewrite $uri=/api/v1/xyz back to just $uri=/xyz
        rewrite ^(.*)$ /$1 break;

        # Try to send static file at $url or $uri/
        # Else try /index.php (which will hit location ~\.php$ below)
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ [^/]\.php(/|$) {
        set $newurl $request_uri;
        # 预设使用 php 7.1 fpm 执行

        fastcgi_pass unix:/run/php/php7.1-fpm.sock;

        if ($newurl ~ ^/(api|old-uri-path1|old-uri-path2)(.*)$) {
            # 变更网站路径为 Laravel 4.2
            root "/home/deploy/laravel4/current/public";
            # 旧网址使用 php 7.0 fpm 执行
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        }

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param REQUEST_URI $newurl;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors off;
        fastcgi_buffer_size 16k;
        fastcgi_buffers 4 16k;
    }


    proxy_intercept_errors on;
    fastcgi_intercept_errors on;

    # gzip
    gzip on;
    gzip_min_length 1000;
    gzip_types  *;
    gzip_comp_level 3;
    gzip_proxied any;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
}

预设是执行 Laravel 5.5,而设定的例外路径则是存取 Laravel 4.2

参考资料