.htaccess,重定向不存在(除了少数 URL 重写)

myt*_*ife 5 .htaccess url-rewriting

我有一个网页,如果用户输入不存在的文件或文件夹http://www.somewebsite.com/nonexistingfolderhttp://www.somewebsite.com/nonexistingfile.html将仅转发到 www .somewebsite.com。然后想创建一个从 www.somewebsite.com/about.html 到 www.somewebsite.com/about 的网页,因为我认为越短越好。使用.htaccess我认为我可以用于RewriteCond不存在的和RewriteRule用户友好的网页 URL。我在 .htaccess 方面很糟糕,我只知道基础知识,我甚至研究了可能已经被问过的问题,但不确定如何编写这个例外规则。

如何添加代码,.htaccess以便可以拥有除我指定的网页网址之外的所有不存在的文件/文件夹?。下面这个将简单地将所有不存在的内容重定向到index.html,当我访问www.somewebsite.com/about(来自/about.html)时,只需转到index.html。有什么帮助吗?

--- my .htaccess shows --
# Redirect non-existing files or folders to index
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ / [L,QSA]
</IfModule>

# Rewrite existing files sample RewriteRule ^contact/$  /pages/contact.htm [L]
RewriteEngine on
RewriteRule ^/$    index.html [L]
RewriteRule ^about/$    about.html [L]
RewriteRule ^services/$    services.html [L]
RewriteRule ^application/$    application.html [L]
RewriteRule ^contact/$    contact.html [L]
RewriteRule ^privacy/$    privacy.html [L]
Run Code Online (Sandbox Code Playgroud)

Jon*_*Lin 2

您需要在所有其他更具体的规则之后进行全有或全无重写(例如 )RewriteRule ^(.*)$ / [L,QSA]。所有规则都按照它们出现的顺序应用,因此这意味着您的第一个规则总是被应用,然后重写引擎停止。

交换顺序并重试:

# Rewrite existing files sample RewriteRule ^contact/$  /pages/contact.htm [L]
RewriteEngine on
RewriteRule ^/?$    index.html [L]
RewriteRule ^about/$    about.html [L]
RewriteRule ^services/$    services.html [L]
RewriteRule ^application/$    application.html [L]
RewriteRule ^contact/$    contact.html [L]
RewriteRule ^privacy/$    privacy.html [L]

--- my .htaccess shows --
# Redirect non-existing files or folders to index
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ / [L,QSA]
</IfModule>
Run Code Online (Sandbox Code Playgroud)

还有这个规则:

RewriteRule ^/$    index.html [L]
Run Code Online (Sandbox Code Playgroud)

永远不会被应用,因为在将规则应用于 URI 之前,前导斜杠已从 URI 中删除,因此^/$永远不会匹配(无论您想要^$还是^/?$相反)。