向Mod_rewrite添加尾部斜杠并在虚拟目录中重定向非尾部斜杠

时间:2012-01-17 00:50:59

标签: .htaccess mod-rewrite

AS有时会发生,我在htaccess文件中创建了我所说的热点。我有几个问题,我知道我偶尔会在内部循环,而且我对此并不擅长。我已经查看了几十个SO问题,并尝试了大量的解决方案。最终的结果是,我正试图将多个单独的解决方案拼凑成一个多部分问题而且我已经弄得一团糟。这几天完全是我的使命。我被卡住了。坏。

  • 我想mydomain.com/handmade-jewelry去mydomain / handmade-jewelry /(注意斜线)
  • 然后我也有.com /手工饰品/饰品去珠宝-nites.php?id = some-piece。这有效,但它也需要一个尾随斜杠。
  • 当我尝试在“/ some-piece /”上显示一个尾部斜杠时,它会重定向并点击未找到的文件。

相信我。我知道我的逻辑中必须有明显的缺陷,我从周六开始就拒绝问这个问题。我知道这是超级常见的问题。我不会问我是不是死了。

( rewrite all www and non-www requests to https:// ...works fine)
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
RewriteCond %{SERVER_PORT} ^80$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

(redirecting to the page with all the jewelry)
RewriteRule ^handmade-jewelry/$ jewelry-inventory-page.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
(following was a failed attempt.) 
# RewriteCond %{REQUEST_URI} !rock-jewelry/(.*)/$
(following works with no trailing slash, which is needed) 
RewriteRule ^handmade-jewelry/(.*)$ jewelry-details.php?s=$1 [L] 
(if I turn this on, it goes to a 404 looking for "handmade-jewelry/this-piece/index.php?s=thispiece/etc...")
# RewriteRule ^handmade-jewelry/(.*)?/$ jewelry-details.php?s=$1 [L]

再次抱歉。我知道很多人,这种问题变得多余了。

1 个答案:

答案 0 :(得分:2)

尝试将以下内容添加到您网站根目录中的htaccess文件

RewriteEngine on
RewriteBase /

#( rewrite all www and non-www requests to https:// ...works fine)
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

#I believe this is redundant because of the previous rule
RewriteCond %{SERVER_PORT} ^80$
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

#if existing file or directory
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
#do nothing
RewriteRule ^ - [L]


#if it does not end with a slash e.g. handmade-jewelry, redirect to with slash
RewriteRule ^([-a-zA-Z0-9]+)$ /$1/ [L,R=301]

#if it does not end with a slash e.g. handmade-jewelry/some-piece, add the slash
RewriteRule ^([-a-zA-Z0-9]+/[-a-zA-Z0-9]+)$ /$1/ [L,R=301]

#(redirecting to the page with all the jewelry)
RewriteRule ^handmade-jewelry/$ jewelry-inventory-page.php [L,NC]

RewriteRule ^handmade-jewelry/([-a-zA-Z0-9]+)/$ jewelry-details.php?s=$1 [L,NC]