背景随着公司的子项目越来越多,大大小小项目也就十几个(仅后端)。按照原来的做法,每次启动一个项目,都必须有一个二级域名映射到对应的项目一般情况下,十个项目就是十个二级域名(不包括测试环境,子-生产环境等),那么多的域名不仅难以管理,更重要的是是一种资源浪费。这个问题困扰了我好久,今天终于解决了这个问题。想记录下坑日记。本文不会讲nginx中各个命令的原理,而是通过实际的项目配置来练习nginx命令的用法,举一反三。提前准备好域名。假设域名为:http://www.dev.com实验环境AliyunECS+centos+Nginx+php-fpm项目11.项目路径:/data/wwwroot/project1/2。访问路径:http://www.dev.com/project1/Project21.项目路径:/data/wwwroot/project2/2。访问路径:http://www.dev.com/project2/Project31.项目路径:/data/wwwroot/project3/2。访问路径:http://www.dev.com/project3/Nginx的location命令涉及的知识点,用法可以参考:https://www.cnblogs.com/coder...Nginx的alias命令,用法可以参考:https://www.jianshu.com/p/4be...实现步骤为了实现上面的访问形式,我们需要用到nginx中的location命令和alias命令,配置如下location^~/${PROJECT}/{别名{$PATH};try_files$uri$uri/@${PROJECT};location~\.php${fastcgi_passunix:/dev/shm/php-cgi.sock;fastcgi_indexindex.php;fastcgi_paramSCRIPT_FILENAME$request_filename;包括fastcgi_params;}}地点@${PROJECT}{rewrite/${PROJECT}/(.*)$/${PROJECT}/index.php?/$1last;}解释:上面配置中的${PROJECT}和{$PATH}都属于到实际过程中需要替换的部分,其中${PROJECT}是url中需要访问的路径部分,比如project1,{$PATH}代表项目真正的访问路径,比如as/data/wwwroot/project1,以http://www.dev.com/project1访问为例,那么对应的Nginx配置就是这个位置^~/project1/{alias/data/wwwroot/project1/public;try_files$uri$uri/@project1;location~\.php${fastcgi_passunix:/dev/shm/php-cgi.sock;fastcgi_indexindex.php;fastcgi_paramSCRIPT_FILENAME$request_filename;包括fastcgi_params;}}location@project1{rewrite/project1/(.*)$/project1/index.php?/$1last;}project2和project3的配置只需要照着上面的配置模板照葫芦画瓢即可。最终完整的nginx配置如下server{listen80;服务器名称www.dev.com;access_log/data/wwwlogs/nginx/access_log/www.dev.com_nginx.log合并;error_log/data/wwwlogs/nginx/error_log/www.dev.com_errr_log;indexindex.htmlindex.htmindex.php;#project1启动配置位置^~/project1/{别名/data/wwwroot/project1/public;try_files$uri$uri/@project1;location~\.php${fastcgi_passunix:/dev/shm/php-cgi.sock;fastcgi_indexindex.php;fastcgi_paramSCRIPT_FILENAME$request_filename;包括fastcgi_params;}}location@project1{重写/project1/(.*)$/project1/index.php?/$1最后;}#project2开始的配置location^~/project2/{alias/data/wwwroot/project2/public;try_files$uri$uri/@project2;location~\.php${fastcgi_passunix:/dev/shm/php-cgi.sock;fastcgi_indexindex.php;fastcgi_paramSCRIPT_FILENAME$request_filename;包括fastcgi_params;}}location@project2{重写/project2/(.*)$/project2/index.php?/$1最后;}#project2开始的配置location^~/project3/{别名/data/wwwroot/project3/public;try_files$uri$uri/@project3;location~\.php${fastcgi_passunix:/dev/shm/php-cgi.sock;fastcgi_indexindex.php;fastcgi_paramSCRIPT_FILENAME$request_filename;包括fastcgi_params;}}location@project3{重写/project3/(.*)$/project3/index.php?/$1最后;}#解析所有.php位置~\.php${fastcgi_passunix:/dev/shm/php-cgi.sock;fastcgi_indexindex.php;fastcgi_paramSCRIPT_FILENAME$document_root$fastcgi_script_name;#fastcgi_paramSCRIPT_FILENAME$request_filename;包括fastcgi_params;不要写访问日志位置~.*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)${expires30d;access_log关闭;}#jscss文件的配置在这里做缓存,缓存7天,不写访问日志位置~.*\.(js|css)?${expires7d;access_log关闭;}location~/\.ht{全部拒绝;}}参考地址如何在localhost下访问多个Laravel项目
