nginx二級目錄反向代理laravel專案,URL::to URL::asset css js生成路徑問題
阿新 • • 發佈:2022-05-19
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的反向代理,只需要做簡單的配置檔案修改就可以解決問題,還不影響線上和開發,是個相對於優雅的解決方案