跳到主要内容

Nginx 域名子目录重定向其他目录

· 阅读需 2 分钟
大刘
一个 web 开发者

例如,example.org域名运行的是 /var/www/top/public 目录中的程序,现在 example.org/blog 需要运行另一个 /var/www/nested/public 目录下的程序。那该怎么操作?

之前有介绍过类似的“单域名下访问多个 Laravel 项目”

localhost multiple laravel

下面介绍 Nginx 下的另一种比较好的方式,还是以 Laravel 应用为例,直接上配置:

server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/top/public;
index index.html index.htm index.php;
server_name _;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location /nested {
alias /var/www/nested/public;
try_files $uri $uri/ @nested;
location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}
}
location @nested {
rewrite /nested/(.*)$ /nested/index.php?/$1 last;
}
location ~ .php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
}
}

配置上后,两个 Laravel 应用都可以正常访问了,但可能出现访问不了 CSS 等静态文件,所以需要添加配置:

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
error_log off;
access_log /dev/null;
}
location ~ .*.(js|css)?$
{
expires 12h;
error_log off;
access_log /dev/null;
}

一切 OK 了,感觉比之前那个方式要安全,就是配置会比较麻烦点,每次增加一个应用,都需要配置一次。

参考:https://serversforhackers.com/c/nginx-php-in-subdirectory