在htaccess中进行URL重写和重定向的确切过程是什么?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在htaccess中进行URL重写和重定向的确切过程是什么?相关的知识,希望对你有一定的参考价值。

我对构建网站非常陌生,并希望了解URL重写和重定向的过程,因为我在htaccess文件中包含的规则并非全部正常工作,我觉得我在这里非常明显。

我试图阅读Apache文档但是我不能完全理解它是编码的新手 - 希望有人能够指出我正确的方向。

我已经重写了我的URL,所以我可以改变URL在浏览器中的显示方式,并使其更加用户/ SEO友好 - 基本上使用下面的代码删除.html

RewriteEngine On
RewriteRule ^skills$ skills.html [NC,L]

上面的规则是完美的工作,并显示漂亮干净的URL。

现在要避免重复的网址(Screaming Frog现在显示重复的网址:技能和技能。)我想用以下方法进行301重定向:

Redirect 301 /skills.html https://www.youmedigital.com/skills

我现在遇到的问题是:所有浏览器都有太多的重定向。我知道,当您从原始URL重定向到新URL时,通常会发生此问题,但不幸的是会陷入无限重定向循环。我尝试通过按照在线教程清除我的cookie来修复它,但它没有帮助。

能帮助我理解一下:1。我是否需要在301重定向之前先重写URL,如上所述?或者首先不需要重写URL,只需要301重定向 - 我尝试了两种解决方案,但没有一种能够正常工作。 2.我的上述规则是否正确,因为我觉得可能我得到的错误显示我搞砸了。

我在htaccess文件中包含了以下所有内容:

#Rewrite everything to https
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#301 redirect to www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^youmedigital.com [NC]
RewriteRule ^(.*)$ http://www.youmedigital.com/$1 [L,R=301]

#301 rewrite url and 301 redirect for clean URL
RewriteEngine On
RewriteRule ^skills$ skills.html [NC,L]

Redirect 301 /skills.html http://www.youmedigital.com/skills

#remove index.html and kill the chance of homepage having duplicates
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /index.(php|html) [NC]
RewriteRule ^index.html$ http://www.youmedigital.com/ [R=301,L]

#remove php and kill the chance of having duplicates
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]

感谢您的帮助!

答案

让我看看你的代码,然后告诉你为什么你得到循环:

RewriteEngine On
RewriteRule ^skills$ skills.html [NC,L]

上面的行将匹配此请求http://yourdomain.com/skills所以,它将被重定向到http://yourdomain.com/skills.html只是添加扩展名。

在你的第二条规则:

Redirect 301 /skills.html https://www.youmedigital.com/skills

你做的是匹配这个请求http://yourdomain.com/skills.html所以,它将被重定向到http://yourdomain.com/skills所以,我想现在你知道为什么循环发生,当第一个规则应用第二个将开始,反之亦然。

为避免这种情况,试试这个:

RewriteEngine On
RewriteCond %{THE_REQUEST} /skills.html [NC]
RewriteRule ^ /skills [NC,L,R=301]
RewriteRule ^skills$   /skills.html [L]

上面的代码将捕获http://yourdomain.com/skills.html请求并将其重定向到http://yourdomain.com/skills外部然后将http://yourdomain.com/skills请求重定向到http://yourdomain.com/skills.html但内部。

清除浏览器缓存然后测试它。

以上是关于在htaccess中进行URL重写和重定向的确切过程是什么?的主要内容,如果未能解决你的问题,请参考以下文章

无法在 .htaccess 中正确重写和重定向 url

htaccess mod_rewrite - 尾部斜线和重定向循环

htaccess 重定向 301 + 重写冲突

目录存在时htaccess重写url重定向

.htaccess重写合并

.htaccess使用URL中的#item重写站点以进行直接文件访问