简体   繁体   English

将301从非斜杠重定向到末尾的斜杠

[英]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/ 我已经在子目录domain.com/blog/中安装了Wordpress,斜杠的问题是,Wordpress帖子为domain.com/blog/post-name和domain.com/blog/post-name/两个版本提供了200 OK http

i want to force trailing slash at the end and redirect 301 from non slash to trailing slash at the end 我想在末尾强制尾随斜杠并将301从非斜杠重定向到末尾斜杠

so trailing slash version gives 200 OK ONLY 因此斜杠版本仅给出200 OK

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. 此正则表达式匹配每个不带任何斜杠的字符串,因此不会匹配domain.com/blog之类的字符串。 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: 如果您使用默认的wordpress htaccess文件 ,则应执行以下操作:

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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