Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在.htaccess中创建重定向的if-else条件_Php_.htaccess_Header Files - Fatal编程技术网

Php 如何在.htaccess中创建重定向的if-else条件

Php 如何在.htaccess中创建重定向的if-else条件,php,.htaccess,header-files,Php,.htaccess,Header Files,基本上,我不能因为请求返回css、js、图像或php字体,因为浏览器会将其读取为html文件,因此,我尝试在.htaccess中执行if-else条件来重定向请求,因此我不必在php中处理这些文件 此外,无论发生什么情况,我都需要强制使用https。 我使用的是Apache/2.2.31,因此无法使用语法 可选的是处理请求头,因此浏览器可以读取真正类型的文件,但我不知道如何读取 我对.htaccess非常陌生,我很确定这应该很容易做到 代码如下: RewriteEngine On #this

基本上,我不能因为请求返回css、js、图像或php字体,因为浏览器会将其读取为html文件,因此,我尝试在.htaccess中执行if-else条件来重定向请求,因此我不必在php中处理这些文件

此外,无论发生什么情况,我都需要强制使用https。 我使用的是Apache/2.2.31,因此无法使用语法

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

我对.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]

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

我想这正是你想要的

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
演示:


文档:

您可以添加您想要实现的重定向作为示例吗?当然,您可以通过php返回您想要的任何内容,只要指定正确的mime类型,只需进行一些小的修改,就可以完美地工作,非常感谢