【问题标题】:.htaccess rewrite rules for multiple cases.htaccess 多种情况的重写规则
【发布时间】:2020-11-06 23:29:00
【问题描述】:

我对我的 url 处理有非常具体的要求,我不知道如何组合所有这些。

如果用户打开http://example.com/abc123,我需要进行以下更改:

  1. http:// 应该变成 https://,然后...
  2. ...如果文件abc123.php存在则打开https://example.com/abc123.php
  3. ...如果目录/abc123/存在则打开https://example.com/abc123/index.php
  4. ...打开https://example.com/index.php?abcdef,即使用abc123作为正常index.php的参数

对于 2. - 4. 我需要地址栏中的 url 保持https://example.com/abc123

到目前为止,我的 .htaccess 中有以下内容,我相信它可以处理 1. 和 2.:

RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L]

【问题讨论】:

标签: .htaccess url redirect mod-rewrite


【解决方案1】:

我面前没有 Apache 服务器,但是这对最后三个有效吗?

# Look for URL.php as a file
RewriteCond %{REQUEST_URI}\.php -f
RewriteRule ^(.*)$ $1.php [L]

# Look for URL as a directory
RewriteCond %{REQUEST_URI} -d
RewriteRule ^(.*)$ /$1/index.php [L]

# If the URL doesn't exist on disk in another way that Apache can
# figure out, forward it to index.hp
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php [QSA,L]

编辑:以下效果很好:

RewriteEngine On

# http:// -> https://
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# -> https://example.com/abc123.php if that file exists
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [END]

# -> index.php if /abc123.php and /abc123/ don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ / [END]

【讨论】:

  • 不幸的是,它没有。以下几乎有效。除了 example.com 本身,它会导致“404 错误 - 找不到对象”RewriteEngine OnRewriteCond %{HTTPS} !=onRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]RewriteCond %{REQUEST_FILENAME}.php -fRewriteRule ^(.*)$ $1.php [END]RewriteCond %{REQUEST_FILENAME}/index.php -fRewriteCond %{REQUEST_FILENAME}/index.php -fRewriteRule ^(.*)$ $1/index.php [END]RewriteRule ^(.*)$ index.php [END](对于可怕的格式表示抱歉^^ )
  • 你能分解每个条件并手动测试每个条件以查看需要调整的内容吗?
  • 基本上,缺少的只是if example.com/abc123 is NOT a folder, redirect to example.com/index.php (without changing the url in the address bar, so I can still read abc123 with Javascript)
  • RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php [END] 不幸的是,这总是重定向到example.com/index.php,即使有一个名为/abc123的目录
  • @TonaldDrump,我已将此答案标记为社区,因此如果您想用您的答案对其进行编辑,我没有得到任何代表,但未来的读者将能够从您的经验中学习。
猜你喜欢
  • 1970-01-01
  • 2017-01-09
  • 2015-02-15
  • 2017-11-21
  • 2011-02-04
  • 2021-02-09
  • 2013-06-29
  • 1970-01-01
相关资源
最近更新 更多