问题原文
原帖链接 · finnandtonic · CC BY-SA 3.0
I have an old site ported from WordPress to basic HTML (don't ask why) and every page is ending in the subdirectory/index.html.
This is causing some funky indexing issues, so I wanted to 301 all the index.html to its parent subdirectory.
So for instance, I would like my pages:
example.com/index.htmlto 301 toexample.com/example.com/service/index.htmlto 301 toexample.com/service/example.com/about-us/index.htmlto 301 toexample.com/about-us
etc, etc.
已采纳解答
原帖链接 · MrWhite · CC BY-SA 4.0
First, a couple of assumptions:
- All your internal links must already point to the non-
index.htmlURL, eg.example.com/service/. (However, since you state that "every page is ending in thesubdirectory/index.html" and you are experiencing some "funky indexing issues, I wonder if this is the case?) - You are using
.htaccesson Apache.
Try something like the following near the top of your .htaccess file:
RewriteEngine On
RewriteCond %{THE_REQUEST} /index\.html
RewriteRule (.*)index\.html$ /$1 [R=301,L]
The check against THE_REQUEST in the RewriteCond directive ensures that only direct requests from the client, that contain index.html, get redirected. THE_REQUEST server variable contains the first line of the request headers and does not get modified when the URL is rewritten. This avoids a potential redirect loop when mod_dir later issues a subrequest for index.html (the DirectoryIndex document) - although this shouldn't be an issue on Apache 2.2+.
However, this could be "simplified" further. The RewriteCond directive could be omitted if using the NS (nosubreq) flag on the RewriteRule directive. The NS flag prevents the rule being processed on "subrequests". As mentioned above, when mod_dir rewrites the URL, it is considered a subrequest. So, by simply including the NS flag, we again avoid a redirect loop. So, the above directives could be replaced with a single RewriteRule directive:
RewriteRule (.*)index\.php$ /$1 [NS,R=301,L]
If you also have a canonical www to non-www redirect then it may be optimal to include the above rule first and specify the canonical absolute domain in the RewriteRule substitution (thus avoiding a potential double redirect). For example:
:
RewriteRule (.*)index\.html$ https://example.com/$1 [R=301,L]
example.com/about-us/index.htmlto 301 toexample.com/about-us
I assume the missing trailing slash on your last example was a typo? The above rule includes a trailing slash (which is required). Omitting the trailing slash introduces additional complexity.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
