【问题标题】:htaccess redirect to index.php & force https/www problemshtaccess 重定向到 index.php 并强制 https/www 问题
【发布时间】:2020-09-27 06:58:03
【问题描述】:

在我的 .htaccess 文件中,我试图实现两件事:-

1) 将任意路径重定向到 /index.php 并将路径作为查询字符串传递,但保留原始 URL

例如example.com/foo/bar 会在后台生成example.com/index.php?foo/bar,但仍会在地址栏中显示example.com/foo/bar 作为URL。

2) 强制 https & www

例如,http://example.com/foo/bar 会在后台生成https://www.example.com/index.php?foo/bar,但会在地址栏中显示https://www.example.com/foo/bar 作为 URL。

以下是我目前所拥有的。

# Redirect to index
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
# When http isn't specified, it redirects to file with same URL
RewriteRule ^(.*)$ index.php?$1 [QSA]

## If no http2
RewriteCond %{HTTPS} off [OR]
## Or if http_host isn't www.
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
## Then rewrite
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=302]

有了这个,如果httpswww 出现在原始 URL 中,重定向到 index.php 就可以正常工作。这是因为只有第一个规则块被触发,而第二个被跳过。

尽管如果httpswww 不存在,地址栏中的结果URL 是https://www.example.com/index.php?foo/bar 而不是https://www.example.com/foo/bar,因为这两个规则块都被触发了。

我想知道这两个不同的 .htaccess 规则块是否可以组合成一个满足原始要求的块?

谢谢

【问题讨论】:

  • 你需要按照相反的顺序做这些事情......首先放置HTTPS重定向,然后内部重写到index.php。
  • @CBroe 说得对。需要维持秩序很重要。为#1 增加了重写规则

标签: .htaccess mod-rewrite


【解决方案1】:

使用这个:

RewriteEngine on
# non www to www 
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# http to https
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

# foo/bar to index.php?a=foo&b=bar

RewriteRule ^([^/]*)/([^/]*)$ /index.php?a=$1&b=$2 [L]

如需更多重写 URL 逻辑,请使用 https://www.301-redirect.online/htaccess-rewrite-generator

推荐工具:https://www.generateit.net/mod-rewrite/

【讨论】:

  • 欢迎。使用此工具进行更长时间的运行会有所帮助
猜你喜欢
  • 1970-01-01
  • 2019-08-12
  • 2018-10-27
  • 1970-01-01
  • 2015-02-12
  • 2016-05-24
  • 2011-10-14
  • 1970-01-01
  • 2016-09-05
相关资源
最近更新 更多