To force (redirect) www.domain.com
to domain.com
in Nginx, you can use the server_name
directive and the return
directive in the server block for your site. Here's an example of how you can set this up:
server { listen 80; server_name www.domain.com; return 301 $scheme://domain.com$request_uri; } server { listen 80; server_name domain.com; # Your other server block directives go here }
In this example, the first server block listens for requests to www.domain.com
and returns a 301 redirect to domain.com
, using the $scheme
and $request_uri
variables to preserve the protocol (http
or https
) and the requested URL path. The second server block listens for requests to domain.com
and contains your other server block directives.
You can also use the rewrite
directive instead of the return
directive to accomplish the same thing:
server { listen 80; server_name www.domain.com; rewrite ^ http://domain.com$request_uri permanent; } server { listen 80; server_name domain.com; # Your other server block directives go here }
The rewrite
directive in this example uses a regular expression to match all requests to www.domain.com
, and returns a permanent (301) redirect to domain.com
, using the $request_uri
variable to preserve the requested URL path.
For more information on the server_name
directive and the return
or rewrite
directives, you can refer to the Nginx documentation.