Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx Remove WWW And Respond To Both

I have the following nginx configuration fragment:

server {    listen 80;     server_name mydomain.io;     root /srv/www/domains/mydomain.io;     index index.html index.php;     access_log /var/log/nginx/domains/mydomain.io/access.log;    error_log /var/log/nginx/domains/mydomain.io/error.log;     location ~\.php {       try_files $uri =404;       fastcgi_index index.php;       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;       fastcgi_intercept_errors on;       fastcgi_pass 127.0.0.1:9000;       include /etc/nginx/fastcgi_params;    } } 

First, how can I make the server block respond to both http://www.mydomain.io and also http://mydomain.io. Second, I want to force if they come from http://www.mydomain.io to redirect to http://mydomain.io.

Thanks.

like image 551
Justin Avatar asked Jul 04 '12 06:07

Justin


People also ask

How do I redirect www NGINX to https?

Nginx Redirect all HTTP traffic to HTTPS Here is a breakdown of the commands: Listen 80 : This instructs the system to catch all HTTP traffic on Port 80. Server_name _; : This will match any hostname. Return 301 : This tells the browser (and search engines) that this is a permanent redirect.

What is rewrite rule NGINX?

NGINX rewrite rules are used to change entire or a part of the URL requested by a client. The main motive for changing an URL is to inform the clients that the resources they are looking for have changed its location apart from controlling the flow of executing pages in NGINX.

What is return 301 in NGINX?

Permanent redirects such as NGINX 301 Redirect simply makes the browser forget the old address entirely and prevents it from attempting to access that address anymore. These redirects are very useful if your content has been permanently moved to a new location, like when you change domain names or servers.


1 Answers

According to https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#server-name-if, you should use:

server {   server_name www.example.com;   return 301 $scheme://example.com$request_uri; } server {   server_name example.com;   # [...] } 
like image 182
Ryan Avatar answered Sep 26 '22 08:09

Ryan