Im trying to setup openresty in ubuntu. every things is working fine, even ssl is also working fine but i didnot find way to redirect www to non www. here is my configurations.
http {
lua_shared_dict auto_ssl 1m;
lua_shared_dict auto_ssl_settings 64k;
resolver 8.8.8.8 ipv6=off;
map $host $no_www_host {
default $host;
"~^www.(.*)$" $1;
}
init_by_lua_block {
auto_ssl = (require "resty.auto-ssl").new()
auto_ssl:set("allow_domain", function(domain)
return true
end)
auto_ssl:init()
}
init_worker_by_lua_block {
auto_ssl:init_worker()
}
server {
listen 443 ssl;
ssl_certificate_by_lua_block {
auto_ssl:ssl_certificate()
}
ssl_certificate /etc/ssl/resty-auto-ssl-fallback.crt;
ssl_certificate_key /etc/ssl/resty-auto-ssl-fallback.key;
location / {
include proxy_params;
proxy_pass http://unix:/run/ecommerce_demo.sock;
}
}
server {
listen 80;
location /.well-known/acme-challenge/ {
content_by_lua_block {
auto_ssl:challenge_server()
}
}
location / {
return 301 https://$no_www_host$request_uri; # Redirect all HTTP to HTTPS
}
}
server {
listen 127.0.0.1:8999;
client_body_buffer_size 128k;
client_max_body_size 128k;
location / {
content_by_lua_block {
auto_ssl:hook_server()
}
}
}
}
2
Answers
To redirect www to non-www in OpenResty, you can achieve this by adding an additional server block in your http configuration. The server block for http://www.example.com should redirect requests to example.com using a 301 redirect, while keeping SSL intact.
You can use this configurations for HTTP to HTTPS redirect.