.htaccess,重定向不存在除了少量URL重写

我有一个网页,如果用户输入不存在的文件或文件夹
http://wwww.somewebsite.com/nonexistingfolder
http://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]

最佳答案 您需要在所有其他更具体的规则之后进行全部或全部重写(例如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>

这个规则也是:

RewriteRule ^/$   index.html [L]

永远不会被应用,因为在向它们应用规则之前从URI中删除了前导斜杠,因此^ / $永远不会匹配,你想要^ $或^ /?$.

点赞