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

走远了吗. 提交于 2020-01-02 22:02:51

问题


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
    RewriteEngine 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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6086876/apache-rewrite-force-https-and-name-of-server-not-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!