[Nginx] location與rewrite配合處理項目的重寫和路徑問題


某個項目中路由是通過$_SERVER['REQUEST_URI']來進行的匹配處理 , 並且隱藏了index.php

前端路徑是http://域名/static/css/xxx.css 而實際路徑是位於 /絕對路徑/template/static中

 

在這樣的兩種情況下 , 不改代碼的條件下使用nginx處理

server {
        listen       80;
        server_name  xxxx;
        root   /var/www/html/admin;
        location / {
            index  index.php;
        }
        location /static {
                root /var/www/html/admin/template;
        }

        if (!-e $request_filename) {
                rewrite ^/((?!static).*)$ /index.php/$1 last;
                break;
        }
        location ~ \.php {

            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            #fastcgi_connect_timeout    10s;
            fastcgi_read_timeout        60s;
            fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO  $fastcgi_path_info;
            fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;
            include        fastcgi_params;
        }
}

最關鍵的是location塊匹配到static后 ,設置了新的root

rewrite正則 , 除去了static , 因為單純的靠!-e $request_filename排除不了 ,因為它路徑是404 , 還是會進判斷 ,只能靠正則了

if (!-e $request_filename) {
rewrite ^/((?!static).*)$ /index.php/$1 last;
break;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM