使用 .htaccess 删除 and/or 重定向和附加参数

Remove and/or redirect and append parameter with .htaccess

有些题的rewrite engine和执行不是很清楚。 在一个小项目中,我在 www root 中有以下结构:

root
  |- index.php      (file)
  |- sandbox.php    (file) 
  |- treehouse.php  (file)
  |- someother.php  (file)
  |- images         (folder)
  |   |- img1.jpg   (file)
  |   |- img2.jpg   (file)
  |   |- img3.jpg   (file)
  |- css            (folder)
  |   |- style.css  (file)  
  |- favicon.ico    (file)

通过我的重写规则,我想实现以下目标:

  1. https://example.com/index.php will be redirected to https://example.com/
  2. 对于已知的 php 文件(index.php 除外,它已经被重定向到 / )应该删除 php 扩展而不是 https://example.com/sandbox.php --> https://example.com/sandbox/
  3. 对于少数 files/urls,参数化 url 应该可以工作。例如沙箱和树屋。 https://example.com/treehouse/magic/place/ should be translated into https://example.com/treehouse.php?param1=magic&param2=place
  4. URL 应以尾 /
  5. 结尾
  6. 应将所有未知文件重定向到根 https:

到目前为止一切顺利。我管理了 1,2 和 5。 对于 3 和 4,我需要来自堆栈智能的一些输入!我试过了,但总是 运行 出错。 工作规则集为:

RewriteEngine On

# remove index
RewriteCond %{THE_REQUEST} /index(\.php)?[\s?/] [NC]
RewriteRule ^(.*?)index(/|$) / [L,R=301,NC,NE]

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]

# To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_URI}.php [L]

# Redirect all not existing to root (index.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ / [R=301,L,QSA]

为了实验,规则在.htaccess 文件中,稍后我打算将它们移动到 Apache Web 服务器的 example.com.conf。 我非常感谢任何支持解决我的问题以及任何改进我现有规则的建议。仅仅因为它有效,并不意味着我应该那样做。

这样说:

RewriteEngine On

# remove index
RewriteCond %{THE_REQUEST} /index(\.php)?[\s?/] [NC]
RewriteRule ^(.*?)index(/|$) / [L,R=301,NC,NE]

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R=301,L]

# add trailing /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]

# 1 param rewrite
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^([\w-]+)/([\w-]+)/?$ .php?param1= [L,QSA]

# 2 param rewrite
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^([\w-]+)/([\w-]+)/([\w-]+)/?$ .php?param1=&param2= [L,QSA]

# To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/.php -f
RewriteRule ^([\w-]+)/?$ .php [L]

# Redirect all not existing to root (index.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . / [R=301,L]