2016-10-01 50 views
1

哪種方法更適合重寫URL重寫URL的更好方法

(a)。使用htaccess的文件,並在使用正則表達式,用於重寫規則

Options +FollowSymLinks 
RewriteEngine On 

RewriteCond %{SCRIPT_FILENAME} !-d 
RewriteCond %{SCRIPT_FILENAME} !-f 

RewriteRule ^users/(\d+)*$ ./profile.php?id=$1 
RewriteRule ^threads/(\d+)*$ ./thread.php?id=$1 

RewriteRule ^search/(.*)$ ./search.php?query=$1 

OR

(B)。 使用htacess文件將每個url重定向到index.php,然後使用PHP進行進一步重定向。

Options +FollowSymLinks 
RewriteEngine On 

RewriteCond %{SCRIPT_FILENAME} !-d 
RewriteCond %{SCRIPT_FILENAME} !-f 

RewriteRule ^.*$ ./index.php 

,之後每個URL可以通過使用index.php$_SERVER['REQUEST_URI']處理,我們可以使用require()語句加載特定文件

哪種方法是安全性和速度的基礎上更好嗎?

回答

0

這種方法更加完善,使用下面的代碼.htaccess文件,並確定要在你的腳本,如訪問您的目錄:JS,CSS或上傳文件夾

RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|assets|**data**|**live**|**css**|**js**|**images**). 

,如果你想要把你的腳本你必須在倒數第二個發言的index.php之前定義的文件夾名稱,我們的文件夾內

RewriteRule ^(.*)$ **anyFolderName**/index.php/$1 [PT,L] 

確保你沒有把任何額外的空間,代號或輸入其它方式重寫模式將不會執行。

注意:還要確保從/ server/apache/apache modules/rewrite_module運行/檢查rewrite_module。

<IfModule mod_rewrite.c> 
# Turn on URL rewriting 
RewriteEngine On 

# If your website begins from a folder e.g localhost/my_project then 
# you have to change it to: RewriteBase /my_project/ 
# If your site begins from the root e.g. example.local/ then 
# let it as it is 
RewriteBase/

# Protect application and system files from being viewed when the index.php is missing 
RewriteCond $1 ^(application|system|private|logs) 

# Rewrite to index.php/access_denied/URL 
RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L] 

# Allow these directories and files to be displayed directly: 
RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|assets) 

# No rewriting 
RewriteRule ^(.*)$ - [PT,L] 

# Rewrite to index.php/URL 
RewriteRule ^(.*)$ /index.php/$1 [PT,L] 
</IfModule> 
0

這取決於您的要求。如果您已經創建了這些php文件,那麼將第一個.htaccess重構爲像這樣的單個規則應該可以正常工作:

Options +FollowSymLinks 
RewriteEngine On 

RewriteCond %{SCRIPT_FILENAME} !-d 
RewriteCond %{DOCUMENT_ROOT}/$1\.php -f 
RewriteRule ^([\w-]+)/(\d+)/?$ $1.php?id=$2 [L,QSA]