5

我有一个网页,如果用户输入不存在的文件或文件夹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以便我可以拥有除我指定的网页 url 之外的所有不存在的文件/文件夹?. 下面的这个将简单地将所有不存在的内容重定向到 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]
4

1 回答 1

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>

还有这条规则:

RewriteRule ^/$    index.html [L]

永远不会被应用,因为在将规则应用到它们之前从 URI 中删除了前导斜杠,所以^/$永远不会匹配,你想要^$^/?$相反。

于 2013-11-06T22:23:52.690 回答