I have 1 subdomain, my routes are all defined in web.php, separated by a subdomain route eg: admin.example.test, example.test
I am hosting my site on valet, i'm trying to make both www and non-www routes to work, non-www seems to be working fine but when i add in www, it will show me "Sorry, the page you are looking for could not be found."
I have also added a htaccess in the public folder to redirect www to non-www site but it doesn't seem to be working:
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
Am i doing something wrong? Shouldn't laravel work with or without the www and not needing a htaccess file?
p/s: it doesn't work on my shared hosting as well with a real domain name
You need to create a suitable CNAME record for intance something like this:
www
mysite.com.
This typically can be done by the gui of your server provider like digital ocean.
I think Laravel should work with subdomain routing, although you'll need duplicate routes: one for the www and another for the non-www version. But you can use the same function for multiple routes. If you would rather use Apache rewrite rules, please read the steps below.
In directory contexts (i.e. in .htaccess
files), the RewriteEngine on
must be set in the file for rewrite rules to work. Also, at server level (i.e. in httpd.conf
file), the Options FollowSymLinks
must be present. The configuration block will be usually like this
<IfModule mod_rewrite.c>
RewriteEngine On
# ... your rewrite rules
</IfModule>
On Apache, the RewriteRule
will be executed only if the two RewriteCond
above are fulfilled. Take a look at the first rewrite condition:
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
%{HTTP_HOST}
is here the hostname of the www route (here admin.example.test
), and must match the pattern ^[^.]+\.[^.]+$
for the rewrite to be performed. But the regex only allows one dot in the hostname. So hostnames with two or more dots (i.e. subdomain.example.test) do not match the regex, hence the rewrite failure from www.example.test. Instead you should use the following to support subdomains:
RewriteCond %{HTTP_HOST} ^[^.]+(\.[^.]+)*$
Maybe not. As you are redirecting from www site to non-www site (maybe from www.example.test to example.test), the RewriteRule
will not work, and instead redirects to www.www.example.test. This is probably not what you want. I think this solution will work:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.[^.]+(\.[^.]+)*$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://yourhostname%{REQUEST_URI} [L,R=301]
where yourhostname
is the hostname of the non-www version. It checks whether the hostname starts with www.
and is also compatible with subdomains. And you don't even have to restart the server as .htaccess files are read each request!