htaccess add .html extension for urls with or without trailing slash

前端 未结 2 795
长情又很酷
长情又很酷 2021-01-15 09:10

So to begin with I have a custom url rewrite that sends a request variable to a php script

Rewrite rule is below:

RewriteRule ^([\\w\\/-]+)(\\?.*)?$          


        
相关标签:
2条回答
  • 2021-01-15 09:59

    This is supposed to redirect /slug-text to /slug-text.html

    RedirectMatch ^/([\w-]+)/?$ http://domein.com/$1.html 
    

    This is in the case when slug-text is only letters, digits, – and _. Rewrite slug-text.html to a php file and pass the slug as a param:

    RewriteRule ^([\w-]+)\.html$ test/index.php?slug=$1 [R,L] 
    

    If you have both line in your .htaccess the first one will do the redirects from the legacy URLs to the new ones and the second one will process the request.

    0 讨论(0)
  • 2021-01-15 10:06

    This rule:

    RewriteRule ^(([\w/\-]+)?[\w-])(/|\.html)?$ test/index.php?slug=$1 [L]
    

    Will trap domain.com/slug-text, domain.com/slug-text/ and domain.com/slug-text.html and send slug-text to /test/index.php inside slug param.

    If you really want to redirect using [R=301] from old urls to new then use this:

    RewriteRule ^(([\w/-]+)?[\w-])/?(?!:\.html)$ http://domain.com/$1.html [L,R=301]
    RewriteRule ^(([\w/-]+)?[\w-])\.html$ test/index.php?slug=$1 [L]
    

    Also note that as using explicit redirect bottom rule is modified to trap url's ending with .html

    It is also advisable (if your .htaccess does not already contain this) to filter conditions for existing files and folders not to be trapped by your redirect rules. Simply add these lines before RewriteRule lines:

    # existing file
    RewriteCond %{SCRIPT_FILENAME} !-f
    # existing folder
    RewriteCond %{SCRIPT_FILENAME} !-d
    

    And if using symlinks:

    # enable symlinks
    Options +FollowSymLinks
    # existing symlink
    RewriteCond %{SCRIPT_FILENAME} !-l
    

    // addition
    Your .htaccess file should look like this:

    RewriteEngine on
    Options +FollowSymLinks
    RewriteCond %{SCRIPT_FILENAME} !-f
    RewriteCond %{SCRIPT_FILENAME} !-d
    RewriteCond %{SCRIPT_FILENAME} !-l
    RewriteRule ^(([\w/-]+)?[\w-])/?(?!:\.html)$ http://domain.com/$1.html [L,R=301]
    RewriteRule ^(([\w/-]+)?[\w-])\.html$ test/index.php?slug=$1 [L]
    
    0 讨论(0)
提交回复
热议问题