2016-04-15 18 views
1

我想在URL中傳遞用戶名,就像Facebook等其他社交網站一樣。 該網址應該是這樣的:www.mysite.com/username創建用戶友好的網址,其中包含用戶名在PHP

另外我希望能夠訪問目錄,如果在用戶名的地方的值是目錄名稱。

Ex。 www.mysite.com/downloads將轉到downloads目錄。

爲此我可以做的是首先檢查傳入的值是一個有效的目錄名稱。如果是,則訪問目錄,否則檢查用戶是否存在傳遞的用戶名。

這是我做的是,創造了.htaccess文件的根目錄包含

RewriteEngine On 
RewriteRule^index.php 

和網址

// requested url 
$request = $_SERVER['REQUEST_URI']; 
// trim last/if available 
$url = rtrim($request,'/'); 
// explode url and save in $ar array 
$ar = explode('/',$url); 

if(sizeof($ar) > 2) 
{ 
    header('location : error/?error=1'); 
} else { 
    $user = $ar[1]; 
} 

的檢查,如果上述說法是檢查傳遞參數一個或多個。例如, www.mysite.com/username/post將導致一個無效的網址

但通過此代碼,我無法訪問我的目錄www.mysite.com/downloads 要做到這一點的簡單方法是什麼。

編輯2:

我想要的網址www.mysite.com/username通過username可變如果不是目錄或myProfile目錄文件index.php它是訪問作爲$user = $_GET['u'];

更新.htaccess

# Do not remove this line or mod_rewrite rules and search engine friendly URLs will stop working 
RewriteBase/
Options All -Indexes 

# Timezone 
SetEnv TZ Asia/Kolkata 

ErrorDocument 404 /404.html 
ErrorDocument 403 /403.html 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ /myProfile/index.php?u=$1 [L,QSA] 
+0

可能的重複[如何在.htaccess中爲用戶配置文件重寫URL](http://stackoverflow.com/questions/6703091/how-to-rewrite-url-for-user-profile-in-htaccess) – Henders

+0

感謝@亨德斯分享鏈接,但在那裏的答案,它給'500內部服務器錯誤'。 –

+0

@anubhava我已經更新了'.htaccess'和一些更多的描述。 –

回答

1

試試這個代碼/.htaccess

ErrorDocument 404 /404.html 
ErrorDocument 403 /403.html 
DirectoryIndex index.php 

RewriteEngine On 
RewriteBase/

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.+)$ myProfile/index.php?u=$1 [L,QSA] 

如果你仍然得到404然後驗證.htaccess是否啓用與否,通過把相同的垃圾(隨機)文本您/.htaccess的頂部,看看它是否在瀏覽器中訪問www.mysite.com/index.php?u=username URL時,會生成500(內部服務器)錯誤。

+0

這是按預期工作,但它正在'www.mysite.com/myProfile/username'上工作,而不是在'www上.mysite.com /用戶名' –

+0

好的嘗試更新的代碼在根.htaccess – anubhava

+1

謝謝,它的工作。 –