作者weiclin (CC)
标题Re: [请益] apache隐藏副档名及http转https
时间Fri Apr 1 05:31:43 2016
※ 引述《Moon008 (008)》之铭言:
: 各位前辈好,
: 最近在测试用Apache架站,希望可以将网页的副档名隐藏起来,并且强制使用https连线
: 假设目前网页有:
: index.php
: about.html
: contact.php
: 我希望呈现的是:
: https://domain.com/ (index.php)
: https://domain.com/about (about.html)
: https://domain.com/contact (contact.php)
: 在使用https之前,我是使用.htacess的方式,放在根目录下,设定为:
: RewriteEngine on
: RewriteBase /
: RewriteRule ^([A-Za-z0-9_-]+)$ $1.html
: 可是这样子没办法辨识该网页应该是.php还是.html
: 不知道有没有办法同时适用?
: 另外就是因为目前希望全站都透过https连线,
: 可是我将上方的规则修改如下之後:
: RewriteEngine on
: RewriteBase /
: RewriteCond %{SERVER_PORT} !443
: RewriteRule ^([A-Za-z0-9_-]+)$ https://%{SERVER_NAME}/$1.html
: 一来是我如果直接输入:domain.com连入,会预设以http连线,
: 且我再点网页上的连结到别页(例如href="about")
: 却会把副档名也加上去(变成https://domain.com/about.html)
: 不知道我的需求使用Rewrite是否可以完全达到呢?
: 因为爬文似乎都是分开说明(针对.php或https)
: 努力结合了几次仍然失败..QQ
: 先谢谢各位了 ><
因为你说你用 Apache 架站, 那就先假设你有完整的控制权
这样子可以把功能拆分到两个 VirtualHost 比较简单
80 port 只要负责把请求原封不动的丢到 https 就行了
整个设定只要这四行:
<VirtualHost *:80>
ServerName example.com
Redirect 301 /
https://example.com/
</VirtualHost>
这个很好用, 因为你不用再去组合你的网址
它会自动帮你把 path 後面的东西贴到 example.com/ 後面去
这边设定的 path 是 /, 等於全部转过去
然後在 port 443 这边放完整的网站设定档
用 rewrite 处理你的隐藏副档名
这边逻辑很简单, 把附档名加上去以後有找到档案的就决定是它了
看你要先找 .html 还是先找 .php 自己调整:
<VirtualHost *:443>
略.....
<Directory 略.....>
略.....
<IfModule rewrite_module>
RewriteEngine On
# 找看看 .htm 档案
RewriteCond %{REQUEST_FILENAME}.html -s
RewriteRule . %{REQUEST_FILENAME}.html [END]
# 再找看看 .php 档案
RewriteCond %{REQUEST_FILENAME}.php -s
RewriteRule . %{REQUEST_FILENAME}.php [END]
</IfModule>
</Directory>
</VirtualHost>
那如果今天你没有 Apache 控制权怎麽办?
或许看完上面的你也能写出来了
但还是给你一个 .htaccess 结合两者的例子
<IfModule rewrite_module>
RewriteEngine On
# 去吧 https, 注意这边用 .*
RewriteCond %{HTTPS} !=on
RewriteRule .*
https://%{SERVER_NAME}%{REQUEST_URI} [END,R=301]
# 找看看 .htm 档案
RewriteCond %{REQUEST_FILENAME}.html -s
RewriteRule . %{REQUEST_FILENAME}.html [END]
# 再找看看 .php 档案
RewriteCond %{REQUEST_FILENAME}.php -s
RewriteRule . %{REQUEST_FILENAME}.php [END]
</IfModule>
使用 rewrite 的技巧之一, 就是不要想把事情一次做完
其实 RewriteCond 就像 if, RewriteRule 就像 then (只是比喻, 实际上...)
所以跟在写程式一样, 可以用很多个 if...then 来拆分
然後这边是用 Apache 2.4 为例, 其中 [END] 这东西在 Apache 2.3.9 後才有
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 210.68.230.200
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/PHP/M.1459459907.A.9B9.html
1F:→ alpe: 没有[END]用[L]吧 [L] 早期就有 04/01 13:31
2F:→ weiclin: 嗯,只是用 [L] 会多跑一轮,增加了出错的机会 04/01 14:29
3F:→ weiclin: 所以能用 [END] 最好 xD 04/01 14:30
4F:推 Moon008: 先谢谢大大回应,但是我照文中後者的作法,会出现重新导 04/02 00:17
5F:→ Moon008: 向次数过多的问题(浏览器).. 04/02 00:17
6F:→ weiclin: 你是怎麽弄的呢? 另外你可以打开 rewrite log 观察行为 04/02 00:30
8F:推 Moon008: 谢谢大大,後来我开log检查一下,再把Rule改写一下就ok了 04/03 01:24
9F:→ weiclin: 哦,如果是我写错了记得指正一下 xD 04/03 06:45
10F:→ pigwolf: 你关闭离开时,直接回信给使用者 04/07 06:46