How can I 301 redirect multiple leading slashes (///file.txt) to just (/file.txt)?

早过忘川 提交于 2019-12-11 10:32:01

问题


I have my apache conf set to show php generated text on a .txt file like so:

Alias /file.txt /var/www/domain.com/html/file.php

The problem is that this now works for any number of leading slashes. For example, all of the following work:

domain.com/file.txt
domain.com//file.txt
domain.com///file.txt

But I'd like all multiple slashes to redirect to the root:

domain.com//file.txt =====[301]=====> domain.com/file.txt

This normally wouldn't be an issue except one of these multiple slashes URLs was actually indexed! Ooops.

Now I need to 301 (permanent) redirect all multiple slashes to the root. (so //file.txt is redirected to /file.txt)

Can you help?


回答1:


When you type in your browser: http://domain.com////////file.txt, the rewrite engine only sees as the URI: /file.txt. However, if you type in your browser: http://domain.com///path////to/////file.txt, the rewrite engine sees the URI as /path////to/////file.txt. The extra leading slashes never show up in the %{REQUEST_URI}, so the only thing you can do is match against the %{THE_REQUEST} variable:

RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /[/]+
RewriteRule ^ %{REQUEST_URI} [L,R=301]

That will only satisfy the extra leading slashes that end up on the browser's address bar, and not stray double slashes that end up somewhere in the URI. To take care of those, you'll need to do something like this:

RewriteCond %{REQUEST_URI} ^(.+)//(.+)$
RewriteRule ^ %1/%2 [L,R=301]


来源:https://stackoverflow.com/questions/11781237/how-can-i-301-redirect-multiple-leading-slashes-file-txt-to-just-file-txt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!