开发者

apache rewrite: force https and name of server, not IP

开发者 https://www.devze.com 2023-03-07 08:21 出处:网络
I want my apache to always force people to use https and to map IP based look ups to be forwarded to the server name. The following settings (in httpd.conf file) take care of the http to https redirec

I want my apache to always force people to use https and to map IP based look ups to be forwarded to the server name. The following settings (in httpd.conf file) take care of the http to https redirect:

<Location />
    Options +FollowSymLinks
    RewriteEng开发者_如何学Cine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://my_server.example.com%{REQUEST_URI}
</Location>

But now I also want that if people type 192.168.1.2 they get redirected to my_server.example.com. To sum up:

http://192.168.1.2/someurl -> https://my_server.example.com/someurl

I've tried several things but either my settings get ignored or I end up in a redirect loop. any hints?


If you have access to the main config and not just .htaccess, this is something most easily done with separate virtual hosts rather than resorting to the Swiss Army chainsaw that is mod_rewrite.

<VirtualHost *:80>
    Redirect permanent / https://my_server.example.com/
</VirtualHost>
<VirtualHost *:443>
    Redirect permanent / https://my_server.example.com/
    SSLEngine on
</VirtualHost>

<VirtualHost *:443>
    ServerName my_server.example.com
    SSLEngine on
    ...real site config...
</VirtualHost>

It's not just numeric IP address access you generally want to redirect to your canonical hostname, but all addresses other than the known-good domains you control. Putting a default virtual host first in the config, that redirects (or serves up nothing) helps avoid certain DNS-based XSS attacks.


I figured out the following solution:

<Location />
    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^my_server\.example\.com [NC]
    RewriteRule (.*) https://my_server.example.com%{REQUEST_URI} [R=301,L]
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://my_server.example.com%{REQUEST_URI}
</Location>

it does exactly what I need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号