如何优化 Nginx 配置以便从子目录为 Laravel 提供服务

如何优化 Nginx 配置以便从子目录为 Laravel 提供服务

我在一个域上设置了多个应用程序,每个应用程序都在自己的文件夹中,如下所示:

  • example.com/app1
  • example.com/app2
  • ...
  • example.com/appX

我的目录树是这样的:

 /usr/share/www/
                root/
                     index.html
                rc/
                   index.php <--- roundcube
                app1/
                     public/
                            css/
                            js/
                            index.php
                appX/
                     public/
                            index.php

其中一个是 Roundcube 网络邮件,其他是 Laravel 应用程序和有一个带有链接和一些信息的单个 html 文件。经过几天的谷歌搜索、阅读文档、服务器故障和堆栈溢出答案,我得出了以下配置,它基本上可以工作,但非常冗长和重复,并且包含指向 laravels 的硬编码路径索引.php脚本。有没有更优雅的解决方案?

   location / {
       root /usr/share/nginx/root;
       index index.html;
       try_files $uri $uri/ =404;
   }

   location /app1 {
        location = /app1/ {
            rewrite ^(.*)$ /app1/index.php last;
        }
        alias /usr/share/nginx/app1/public;
        index index.php;
            if (-f $request_filename) {
             break;
            }
        rewrite ^(.*)$ /app1/index.php last;
    }        

location ~ /app1/.+\.php$ {
            root /usr/share/nginx/app1/public;
            include fastcgi_params;
            fastcgi_intercept_errors off;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_param SCRIPT_FILENAME /usr/share/nginx/app1/public/index.php;
            fastcgi_param HTTPS on;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
    }
# And others like above with adjusted paths

# Setup Roundcube
    location ^~ /rc {
    root /usr/share/nginx;
    index index.php;
    try_files $uri $uri/ =404;

    location ~ /rc/.+\.php$ {
        root /usr/share/nginx/rc;
        rewrite /rc/(.*)$ /$1 break;
        include fastcgi_params;
        fastcgi_intercept_errors off;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS on;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
    }

    location ~ /rc/favicon.ico$ {
        root /usr/share/nginx/rc/skins/default/images;
        log_not_found off;
        access_log off;
        expires max;
    }

    location = /rc/robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ ^/rc/(README|INSTALL|LICENSE|CHANGELOG|UPGRADING|README\.md|composer\.json-dist)$ {
                deny all;
            }

    location ~ ^/rc/(bin|SQL)/ {
                deny all;
            }


    }        

# Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
location ~ /\. {
            deny all;
            access_log off;
            log_not_found off;
    }

相关内容