各位好,我今天想利用 nginx 达到同一个 domain 经由不同的子路径连到不同的 Laravel 专案:

  • http://24.test/cms1 -> /var/www/cms1/public
  • http://24.test/cms2 -> /var/www/cms2/public

以下是我目前的配置:

server {
listen 80;
server_name 24.test;

root /var/www/cms1/public/;
index index.php;

location ~ \\.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;
}

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

location /cms1 {
alias /var/www/cms1/public/;
index index.php;

location ~ \\.php$ {
fastcgi_index index.php;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME /var/www/cms1/public$fastcgi_script_name;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;

try_files $uri $uri/ /cms1/index.php?$query_string;
}
}

location ~ /\\.ht {
deny all;
}
}

root 的配置我是用来测试 php-fpm 以及 Laravel 专案是否有正常执行,测试是正常的可以连到,测试 /cms1 时我会注解掉以防干扰,但目前这样配置连到 cms1 会得到 File not found.,应该就是传送到 php-fpm 的路径有误导致无法正确执行,想请教这块怎么配置才对,谢谢。

1 个回答

2

㊣浩瀚星空㊣

iT邦大神 1 级 ‧ 2025-01-06 14:40:46

不要用路径区分,很难处理。
我大多是用子域名来应用。反正也只是设定 host

以下是我的 nginx 设定

server {
	listen 80;
	listen [::]:80;

	server_name test.com *.test.com;
	
    	
	set $root "/var/www";
    	if ($host ~ ^(\\w+)\\.test\\.com$) {	        
	        set $root "/var/www/$1";
    	}
    	
	root $root;
	
	location ~ \\.php$ {
		fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
		fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
		include fastcgi_params;
		fastcgi_hide_header X-Powered-By;
	}

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

这样不同子域名就会在各自的目录区内。开发很方便。
开新专案,再去 host 加上就行。


  • 2

chan15

iT邦新手 2 级 ‧
2025-01-06 15:53:05

目前也是决定用不同域名了,路径大小问题不断

修改

㊣浩瀚星空㊣

iT邦大神 1 级 ‧
2025-01-06 16:23:26

上面的设定
其实我自已是使用实体域名。然后设定成多子域名的模式。
所以我只要建新专案。目录名就是我的子域名。
也不需要再来设定nginx了。

修改