-1

How to redirect an URL such as http://192.0.2.4 to https://example.com and not https://192.0.2.4 in Nginx?

Like Google is doing by redirecting https://172.217.7.206 to https://google.com

My nginx configuration:

#Redirect all traffic to HTTPS

  server {
  listen 80 default_server;
    return 301 https://$host$request_uri;
    } 

 server {

    listen 443 ssl http2;
    server_name  www.example.com;

I don't want any rewrite because it cost more resources.

Patrick Mevzek
  • 10,995
  • 16
  • 38
  • 54
  • when you redirect to $host you redirect to the same host that has arrived. if you want to redirect to your own host, return 301 https://example.com$request_uri; to redirect to the host you want. – flaixman Dec 31 '18 at 21:52
  • Sorry but because of the ip address is not accepted by ssl, nginx is not redirecting the HTTPS request. – Abduιιαh Jan 01 '19 at 19:31
  • Isn't the answer I just put down there right? – flaixman Jan 01 '19 at 19:33
  • I just found an answer on another question, actually It's not possible through nginx. https://stackoverflow.com/questions/50258202/how-does-google-force-https-on-their-app-tld/50258651#50258651 – Abduιιαh Jan 01 '19 at 19:35
  • I thought you asked this: https://serverfault.com/questions/629045/nginx-redirect-ip-address-to-domain-name Close, the question if it's already asnwered, and great you managed to find it, thanks for the info :D – flaixman Jan 01 '19 at 19:37
  • Your answer is right for HTTP request, not HTTPS. – Abduιιαh Jan 01 '19 at 19:39
  • Oh, okay, someone edited it and put it as "http" , just edited it to be clear that you want https and not http. – flaixman Jan 01 '19 at 19:41

1 Answers1

0

Redirect all traffic to HTTPS

If the only domain you recive in your server is www.example.com, this solution should work for you. This listens to the "ip" and redirects it to www.example.com.

server {
    server_name 192.0.2.4;
    return 301 https://www.example.com$request_uri;
} 
flaixman
  • 702
  • 6
  • 14