2016-07-04 188 views
2

比方說,我有一個名爲careers.php文件,我怎麼爲這個文件,當他們點擊進入http://example.com/careers沒有兩個.html.php文件與nginx的文件擴展名的鏈接?如何從nginx中的URL中刪除文件擴展名?

  1. 請注意,該解決方案必須考慮查詢字符串。例如,URL可能是http://example.com/careers?lang=fr

  2. 此外,我想解決方案也嘗試子目錄以及。例如;如果服務器上的我的文件夾結構是/views/careers.php,我想http://example.com/careers仍然服務於/views/careers.php

我現在的配置如下所示:

server { 
    listen 80 default_server; 

    root /usr/share/nginx/landing-page; 
    index index.php index.html; 

    server_name example.com; 

    location/{ 
     try_files $uri $uri/ =404; 
    } 

    error_page 404 /404.html; 
    error_page 500 502 503 504 /50x.html; 

    location ~ \.php$ { 
     try_files $uri =404; 
     fastcgi_split_path_info ^(.+\.php)(/.+)$; 
     fastcgi_pass unix:/var/run/php5-fpm.sock; 
     fastcgi_index index.php; 
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
     include fastcgi_params; 
    } 
} 

回答

1

一個共同的解決方案使用try_files與命名的位置。現有的location ~ \.php$塊用於處理.php文件。還要避免任何if陳述。

location/{ 
    try_files $uri $uri/ @rewrite; 
} 
location @rewrite { 
    rewrite^$uri.php last; 
} 
location ~ \.php$ { 
    try_files $uri =404; 
    ... 
} 
1

您可以使用try_files

try_files $uri $uri.php $uri/ =404; 
+0

'try_files $ uril $ uri.php /views/$uri.php $ uri/= 404;'爲我的第二點工作?此外,這將允許查詢字符串? –

+1

@EdwardMaxedon是的,查詢字符串將不受影響。對於第二點,考慮到'$ uri'將包含前導斜槓 – Vasfed

+0

我現在已經注意到,而不是將文件作爲.php文件處理,它在我訪問該頁面時下載。 'location〜\ .php $'塊是否需要更新? –