【问题标题】:How to make a if else conditions to redirect in .htaccess如何使 if else 条件在 .htaccess 中重定向
【发布时间】:2019-11-25 13:08:30
【问题描述】:

基本上,由于请求,我无法使用 php 返回 css、js、图像或字体,因为浏览器将其作为 html 文件读取,因此,我试图在.htaccess 来重定向请求,所以我不必在 php 中处理那些文件。

此外,无论如何我都需要强制使用 https。 我使用的是 Apache/2.2.31,所以我不能使用语法<If "true"> </If>

可选的是处理请求头,所以浏览器可以读取文件的真实类型,但我不知道如何。

我是 .htaccess 的新手,我很确定这应该很容易。

代码如下:

RewriteEngine On

#this is just to forcing https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301]

# if css, js, html, images and fonts, do not redirect anything
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png|woff?2|otf|html)$ [NC]
RewriteRule  # I don't know how to do anything

# else if the folder is “admin”, don’t do anything
RewriteCond %{THE_REQUEST} /admin/([^\s?]*) [NC] 
RewriteRule  # I don't know how to do anything

# else if the file is php or a folder, redirect to public folder
RewriteRule ^ %1 [L,NE,R=302]
RewriteRule ^((?!public/).*)$ public/$1 [L,NC]

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 可以添加你想要实现的重定向作为例子吗?
  • 当然你可以通过php返回任何你想要的内容,只是html,如果你指定了正确的mime类型 ...

标签: php .htaccess header-files


【解决方案1】:

我想这是你想要的非常接近的地方

RewriteEngine On

# this is just to forcing https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

# IF the folder is “admin”, don’t do anything
    RewriteCond %{REQUEST_URI} /admin/(.*) [NC]
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]
# END IF

# IF the file is PHP or a folder, redirect to the public folder
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_URI} ^(.*)\.php$ [NC]
    RewriteRule ^(.*)$ "https://%{HTTP_HOST}/public/$1" [R=302,L]
# ELSE if file is css, js, html, images and fonts, do not redirect anything
    # Do nothing
# END IF

重定向结果:

http://example.com/admin/index.php --> https://example.com/admin/index.php
http://example.com/index.php --> https://example.com/public/index.php
http://example.com/main.js --> https://example.com/main.js

演示:https://htaccess.madewithlove.be?share=9a712335-897f-57d3-9127-3bc5d747c0a7

文档:https://httpd.apache.org/docs/2.4/rewrite/remapping.html

【讨论】:

  • 稍作修改,完美运行,非常感谢
猜你喜欢
  • 1970-01-01
  • 2019-04-25
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2019-12-28
  • 2018-09-12
  • 1970-01-01
相关资源
最近更新 更多