2017-12-18 291 views
0

我很難得到永久重定向工作。我希望使用正則表達式來實現這一點。htaccess正則表達式301重定向

舊的URL:https://example.com/olddir/other_name_here/123456/garbage.jpg

新的URL:https://example.com/newdir/other-name-here-123456/

注意從下劃線的變化,以破折號和我的數字串後扔額外位了一個事實。我試過這個,但它不工作(頁面不存在,仍然404):

RewriteRule ^/olddir/other_name_here /([0-9] {6})/.+/newdir/other-name-here- $ 1/[R = 301,L]

我在「other_name_here」目錄位置有幾百個名稱,所以如果我可以動態地將下劃線改爲連字符,那會很好但不是必要的。 olddir和newdir是實際名稱,可以進行硬編碼。我究竟做錯了什麼?謝謝!

+0

你添加以下行到你的'.htaccess'文件和'RewriteRule'過嗎? 第1行:'選項+ FollowSymLinks' 線路2:'RewriteEngine敘述On' 後還你''加'$'([0-9] {6})/.+' 最後但並非最不重要的,你確定你的新URL存在嗎(該文件在服務器上可用)? – Allan

回答

0

請嘗試以下操作:

  • 如果未出現在.htaccessRewriteRule之前添加下面兩行:

    Options +FollowSymLinks 
    RewriteEngine On 
    
  • 通過添加$改變你的正則表達式通過以下方式:

    RewriteRule ^/olddir/other_name_here/([0-9]{6})/.+$ /newdir/other-name-here-$1/ [R=301,L] 
    
  • 嘗試直接訪問新的URL頁面並確認它們可以訪問。

最後,我建議這個網站有關.htaccess詳細配置信息:https://mediatemple.net/community/products/dv/204643270/using-htaccess-rewrite-rules