php 去掉Url裏的 index.php

php項目中,爲了訪問鏈接的友好性及SEO優化,我們經常需要爲訪問頁面配置一個短鏈接,並把index.php去掉。
php所用的web服務器通常爲:nginx或者apache。下面分別說一下兩種服務器的不同配置方法

NGINX 配置:
1、打開nginx配置文件:/usr/local/nginx/conf/nginx.conf
2、修改文件,有兩種語法
A:

location / {
     try_files $uri $uri/ /index.php?q=$uri&$args;
}

B:

location / {
       if (!-e $request_filename) {
            rewrite ^/(.*)$  /index.php?q=$uri&$args;
       }
}

如果根目錄爲二級目錄,則需要做對應修改:
A:

location /cn/ {
          try_files $uri $uri/ /cn/index.php?q=$uri&$args;
  }

B:

location /cn/ {
       if (!-e $request_filename) {
             rewrite ^/cn/(.*)$  /cn/index.php?q=$uri&$args;
       }
}

3、檢查Nginx是否有語法錯誤,無錯誤則重啓

#檢查是否有語法錯誤
/usr/local/nginx/sbin/nginx -t
#重啓nginx
/usr/local/nginx/sbin/nginx -s reload

Apache 配置:
1、httpd.conf配置文件中加載了mod_rewrite.so模塊

#LoadModule rewrite_module modules/mod_rewrite.so   把前面的 # 去掉

2、修改httpd.conf配置文件:
AllowOverride None 中將None改爲 All
(注意其他地方的AllowOverride也統統設置爲ALL)

    AllowOverride none  改   AllowOverride ALL
    Options None
    Order allow,deny
    Allow from all

3、.htaccess文件必須放到跟目錄下
.htaccess 文件內容

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
發佈了36 篇原創文章 · 獲贊 4 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章