简体   繁体   中英

Redirect 301 from non trailing slash to trailing slash at the end

I've installed Wordpress in subdirectory domain.com/blog/ The problem with the trailing slash , Wordpress posts gives 200 OK http for the two versions domain.com/blog/post-name and domain.com/blog/post-name/

i want to force trailing slash at the end and redirect 301 from non slash to trailing slash at the end

so trailing slash version gives 200 OK ONLY

my code

# Force Trailing Slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301]

The problem with your code is at the regex: ^[^/]+$

This regex matches every string without ANY slash, so a string like domain.com/blog would not match. The best way to achieve your goal is like the following:

# Force Trailing Slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^(.*)[^/]{1}$
RewriteRule (.*) $1/ [L,R=301]

If you are using the default wordpress htaccess file you should do like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Force Trailing Slash
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} ^(.*)[^/]{1}$
    RewriteRule (.*) $1/ [L,R=301]


    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

</IfModule>
# END WordPress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM