nginx 同一域名下配置 yii2 的 frontend 和 backend

更新日期: 2018-02-22 阅读次数: 13186 分类: Nginx

第一次看 yii2 的代码结构,非常不适应。居然 frontend 和 backend 分成了两个独立的文件夹。。。完全没有我大 laravel 的优雅之风。

而且大兄弟是用的 YiiBoot 这种冷门的东西。YiiBoot 类似于 Laravel 的 Backpack,使用 Yii2 + AdminLTE + mysql,开发高效的通用管理后台,同时可以自动生成 model controller 的代码。)

设置了 common\config\main.php 中的 MySQL 配置之后,就是 Nginx 配置了。

Github 上找到一个配置,稍作修改就能运行起来了。

server {
    listen 80;
    server_name www.sunzhongwei.com;

    set $base_root /path/to/project;
    root $base_root;

    index index.php index.html;

    location / {
	# root 会将 location 匹配的路径缀在 root 参数的后面
	# 如果,前端兄弟把前端资源路径写死成了 /frontend/web/assets/xxxx
	# 那么就把下面这行注释掉吧
        root $base_root/frontend/web;			
        try_files $uri $uri/ /frontend/web/index.php$is_args$args;

        # omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
        #location ~ ^/.+\.(css|js|ico|png|jpe?g|gif|svg|ttf|mp4|mov|swf|pdf|zip|rar)$ {
        #    log_not_found off;
        #    access_log off;
        #    try_files $uri =404;
        #}

        location ~ ^/assets/.+\.php(/|$) {
            deny all;
        }
    }

    location /admin {
	# 管理后台
        alias $base_root/backend/web/;

        # redirect to the URL without a trailing slash (uncomment if necessary)
        #location = /admin/ {
        #    return 301 /admin;
        #}

        # prevent the directory redirect to the URL with a trailing slash
        location = /admin {
            # if your location is "/backend", try use "/backend/backend/web/index.php$is_args$args"
            # bug ticket: https://trac.nginx.org/nginx/ticket/97
            try_files $uri /backend/web/index.php$is_args$args;
        }

        # if your location is "/backend", try use "/backend/backend/web/index.php$is_args$args"
        # bug ticket: https://trac.nginx.org/nginx/ticket/97
        try_files $uri $uri/ /backend/web/index.php$is_args$args;

        # omit static files logging, and if they don't exist, avoid processing by Yii (uncomment if necessary)
        #location ~ ^/admin/.+\.(css|js|ico|png|jpe?g|gif|svg|ttf|mp4|mov|swf|pdf|zip|rar)$ {
        #    log_not_found off;
        #    access_log off;
        #    try_files $uri =404;
        #}

        location ~ ^/admin/assets/.+\.php(/|$) {
            deny all;
        }
    }

    location ~ ^/.+\.php(/|$) {
        rewrite (?!^/((frontend|backend)/web|admin))^ /frontend/web$uri break;
        rewrite (?!^/backend/web)^/admin(/.+)$ /backend/web$1 break;

       include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock; 
    }

    location ~ /\. {
        deny all;
    }
}

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式