在NGINX上运行Laravel和AngularJS

时间:2014-07-16 02:58:53

标签: angularjs laravel nginx laravel-4

我为后端运行Laravel,为前端运行AngularJS。我的应用程序层次结构是

/application
    /app
    /bootstrap
    /vendor   
    /public
        /api 
            index.php <-- This is the Laravel "public" index
        index.html
        bootstrap.js

基本上,默认的public文件夹用于AngularJS前端,/public/api用于Laravel。

我无法弄清楚如何编写NGINX配置!这就是我到目前为止所拥有的

server {
        listen   80;

        root PATH_TO_PUBLIC;
        index index.php index.html index.htm;

        server_name mysite.com;

        # AnuglarJS UI Front /index.html
        location / {
                try_files $uri $uri/
        }

        # Laravel Back-end /api/index.php
        location /api/ {
                try_files $uri $uri/ /index.php$is_args$args;
        }

        error_page 404 /404.html;

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
              root /usr/share/nginx/html;
        }

        # pass the PHP scripts to FastCGI server listening on the php-fpm socket
        location ~ \.php$ {
                try_files $uri / =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}

Laravel唯一有效的页面是/api/index.php。甚至像/api/index.php/my-resource这样的东西也不起作用。

修改

当我访问/api/index.php时,Laravel开始工作并开始工作。当我访问任何其他页面(例如/api/sessions/api/index.php/sessions时,它会加载主页/index.html

1 个答案:

答案 0 :(得分:0)

我的情况与你的情况略有不同,因为我已尽力将Angular和Laravel应用程序保存在不同的目录中,并且在单独的源代码控制中,但我面临着与你完全相同的挑战,而我解决方案如下。

关键区别在于.php $位置使用“alias”。它告诉nginx使用不同的基本路径来开始查找文件,这将有助于它正确地找到index.php。这是必要的,因为Angular和Laravel需要引用来自不同基本路径的文件。

server {
    listen   80;

    root /path/to/application/app/public; # Path to Public
    index index.php index.html index.htm;

    server_name mysite.com;

    # AnuglarJS UI Front /index.html
    location / {
        try_files $uri $uri/
    }

    # Laravel Back-end /api/index.php
    location /api/ {
        try_files $uri $uri/ /index.php$query_string; # Minor adjustment here - a simpler solution that achieves the same thing
    }

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    # pass the PHP scripts to FastCGI server listening on the php-fpm socket
    location ~ \.php$ {
        #---------------------------------------------------------------
        alias /path/to/application/app/public/api; # Path to directory containing index.php
        #---------------------------------------------------------------                try_files $uri / =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}