单域名(localhost)下访问多个 Laravel 项目
一个服务器不能配置多个子域名的时候很是尴尬,无法使用虚拟目录,只能通过二级目录访问。在根目录 /data/wwwroot/default
部署了多个 Laravel 应用,例如 laravel1
,laravel2
…,然后按文档配置所谓的优雅链接,遇到了诸多问题:
- Apache 服务器:XAMPP 的 LAMP 环境
- Nginx 服务器:OneinStack 自动部署 LNMP 环境
Apache 服务器
在 LAMP 环境下使用还是蛮简单,配置 Laravel/public/.htaccess
:
apache
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
即可,访问的地址:
Nginx 服务器
文档中说,只要在 nginx.conf
下配置:
nginx
location / {
try_files $uri $uri/ /index.php?$query_string;
}
即可,访问优雅链接,但结果有点失望,你会遇到问题:
- Access denied.
- No input file specified.
- 504
- …
归根结底是 nginx.conf
配置问题,本人遇到最多就是 Access denied,因为使用 OneinStack 自动部署 LNMP 环境,nginx.conf
已经默认配置了,结果仔细对比,少了下面配置
nginx
fastcgi_split_path_info ^(.+.php)(.*)$;
难怪 Laravel 优雅链接 index.php
后面一直无法访问,目前问题已解决,附上一段网上的配置:
nginx
server {
listen 80;
server_name _;
set $root_path '/data/www/default';
root $root_path;
index index.php index.html index.htm;
try_files $uri $uri/ @rewrite;
location @rewrite {
rewrite ^/(.*)$ /index.php?_url=/$1;
}
location ~ .php {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index /index.php;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
root $root_path;
}
location ~ /.ht {
deny all;
}
}
http://test.com/laravel1/public/index.php/admin/index
http://test.com/laravel2/public/index.php/admin/index
都可以正常访问了,OK!
最后隐藏 index.php
虽然上述配置在 Laravel 中可以正常访问,但是一些放在 public
里面的静态资源可能无法访问,比如无法使用 asset()
函数时,路径中就包含 index.php
导致资源无法加载,所以建议隐藏 index.php
nginx
if (!-e $request_filename) {
rewrite ^/(.*)/public/(.*)$ /$1/public/index.php/$2 last;
# 或者
rewrite ^/(.*)/public/ /$1/public/index.php?$query_string last; # 推荐
break;
}
http://test.com/laravel1/public/admin/index
http://test.com/laravel2/public/admin/index
以上就无需加 index.php
,即可正常访问。