2013-11-14 22 views
1

我想在nginx中重寫url,以便.php擴展名可以省略。從url中刪除.php與重寫規則

這是我的,但這不適合我。任何人有任何想法如何做到這一點?

謝謝。

server { 
     listen 80; 
     server_name example.com; 
     return 301 $scheme://www.example.com$request_uri;  
} 

server { 
     listen 80; 
     root /usr/share/nginx/www; 
     index index.php; 
     server_name www.example.com; 
     error_page 404 http://www.example.com/404.php; 
     autoindex off; 
     error_log /usr/share/nginx/www/nginx_error.log warn; 

    location/{ 
     rewrite ^(.*)$ /$1.php; 
    } 

    location =/{ 
     rewrite^/index.php; 
    } 

    location ~ \.php$ { 
     include fastcgi_params; 
     fastcgi_pass unix:/var/run/php5-fpm.sock; 
    } 

} 

這是我的整個配置文件。

回答

2

@Makromat我覺得404的問題,你的意見提的是,你的/位置解析爲/.php沒有文件名,所以要解決這個問題,我們可能會添加其他位置只是爲了處理這種特殊情況

location/{ 
    rewrite ^(.*)$ /$1.php; 
} 
location =/{ 
    rewrite^/index.php; 
} 

試試這個,告訴我,如果它的工作原理

編輯:

好刮,我有更好的想法,如果原始網址已包含.php擴展因此最好將其定義爲一個回落的解決方案第一種情況下會失敗,試試這個

location/{ 
    try_files $uri $uri.php $uri/; 
} 

嘗試替換此與您當前的php塊

location ~ \.php$ { 
    include fastcgi_params; 
    fastcgi_pass unix:/var/run/php5-fpm.sock; 
} 
+0

您的第一個解決方案相對工作,但我沒有任何css風格。重定向工作,但當我點擊菜單項(其中只有一個從5項)imediatelly是下載的PHP文件,但其他四個菜單項正常工作:D這真的很瘋狂。 (我愛.htaccess) – Makromat

+0

當我嘗試你的第二個解決方案...如果我點擊任何菜單項我的瀏覽器下載php文件... – Makromat

+0

什麼是你的php塊在配置 –

0

這樣的事情應該是你在找什麼。

location ^/(.*)$ { 
    rewrite ^(.*)$ /$1.php; 
} 
+0

感謝,但是當我重新啓動nginx的我有錯誤:'重新啓動nginx的:nginx的:EMERG]意外的 「}」 在/ etc/nginx的/啓用的站點 - /默認:42 nginx:配置文件/etc/nginx/nginx.conf測試失敗# – Makromat

+0

糟糕,忘記了.php後的分號。 –

+0

非常感謝Deniz!現在它的工作,但我的主頁顯示錯誤404 ...但在菜單中的每個項目是功能...只/不工作... – Makromat

3

花了一段時間,試圖讓這個工作正常。這兩個PHP文件和其他資源工作:

location/{ 

    if (!-e $request_filename){ 
     rewrite ^(.*)$ /$1.php; 
    } 
    try_files $uri $uri/ /index.php?$query_string; 
} 
+0

這種安全嗎?關於此:https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#passing-uncontrolled-requests-to-php和https://nealpoole.com/blog/2011/04 /設置-UP-PHP-FastCGI的-和nginx的,不要信任最教程 - 檢查 - 你的配置/ – Snowball