是否有一个Apache变量只包含文件名-没有路径

cl25kdpy  于 2023-04-21  发布在  Apache
关注(0)|答案(1)|浏览(177)

我有很多这样的重定向:

RewriteRule ^demos/(bar-3d-effect-multi-row\.html)        demos-website/$1
RewriteRule ^demos/(bar-adjustable\.html)                 demos-website/$1
RewriteRule ^demos/(bar-ajax\.html)                       demos-website/$1
RewriteRule ^demos/(bar-basic\.html)                      demos-website/$1
RewriteRule ^demos/(bar-dark-background\.html)            demos-website/$1
RewriteRule ^demos/(bar-google-power-usage\.html)         demos-website/$1
RewriteRule ^demos/(bar-i-love-my-dog-de-bordeaux\.html)  demos-website/$1
RewriteRule ^demos.(bar-images-as-labels\.html)           demos-website/$1
RewriteRule ^demos/(bar-interactive-key\.html)            demos-website/$1
RewriteRule ^demos/(bar-line-switch-effect\.html)         demos-website/$1

...

有没有一种方法可以将所有这些重定向压缩成几行?也许像这样:

RewriteCond ^demos-website/%{FILENAME} -f
RewriteRule ^demos/%{FILENAME}   /demos-website/%{FILENAME}

这样,它只重写URL,如果该文件存在于demos-website目录?

lymgl2op

lymgl2op1#

请注意,正则表达式可能存在问题,因为我自己无法很好地测试它,使用它的风险自担:

# sets filename to the file name
RewriteRule ^demos\/.*?([^\/]+)\/*$ - [ENV=filename:$1]
# checks if the file exists in the other directory
RewriteCond %{DOCUMENT_ROOT}/demos-website/%{ENV:filename} -f
# redirect if it is true
RewriteRule ^demos/ /demos-website/%{ENV:filename} [R,L]

您可以参考https://httpd.apache.org/docs/2.4/expr.html#vars以获取可用于mod_rewrite的变量。

相关问题