nginx二级目录反向代理laravel项目,URL::to URL::asset css js生成路径问题

2022年5月18日17:00:29

 

最近在做微信 h5项目,因为业务域名必须是同一个,php的请求由nginx反向代理,通常是不需要写页面的,但是因为时间不够,就套几个页面

 

 location /weixin/ {
            proxy_pass http://127.0.0.1:9000/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Remote_addr $remote_addr;
        }


        location /weixintest/ {
            proxy_pass http://127.0.0.1:9011/;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Remote_addr $remote_addr;
        }

 

但是上测试的时候发现反向代理过去的请求会导致js css等静态文件访问不到,生成的连接不带反向代理过去的目录的的前缀

location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
{
    proxy_pass http://127.0.0.1:9011/;
    expires 12h;
}

最开始想通过吧反向代理的js css文件,虽然这样静态文件可以了

 

发现异步请求的接口还是有问题,我又想吧请求协成固定,发现写出来很有问题

最后发现URL::to 方法是可以设置前缀的

 

在 AppServiceProvider 里面增加

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\URL;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
//        Schema::defaultStringLength(191);
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //设置 https 还是https 测试的时候注销掉
        URL::forceScheme(env('APP_URL_HTTPS'));
        //url前缀,在nginx反向代理的时候,生成文件路径没有二级代理目录的问题,本地测试 APP_URL为空,开发测试填写带路径的 URL: https://www.yd.com/weixintest/
        URL::forceRootUrl(env('APP_URL'));
    }
}

 

在 .env里面添加

本地开发

APP_URL= #APP_URL_HTTPS=https #APP_URL=https://www.yd.com/weixintest/


测试或者线上

#APP_URL=
APP_URL_HTTPS=https
APP_URL=https://www.yd.com/weixintest/

URL::to URL::asset 相关方法就不会有问题

最后在不修改的nginx的反向代理,只需要做简单的配置文件修改就可以解决问题,还不影响线上和开发,是个相对于优雅的解决方案

 

posted on 2022-05-19 09:08  zh7314  阅读(472)  评论(0编辑  收藏  举报