简体   繁体   中英

How to redirect example.com and example.com/anything to example.com/blog

I want to redirect example.com and example.com/anything to example.com/blog. Please note few things.

I refer example.com for a 1 domain.

I use apache as web server.

My document root is set to /var/www/html/public within apache vhost conf file (For a laravel APP).

I tried setting redirects in .htaccess and using apache vhost conf file and I get redirect too many times error.

Can someone help me to accomplish this please?

This probably is what you are looking for: rewriting on the level of the http server:

RewriteEngine on
RewriteRule ^/?$ /blog [R=301]
RewriteRule ^/?anything/?$ /blog [R=301]

If by "anything" you actually mean anything so that a redirection should get applied regardless of the requested path, then this should do:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/blog
RewriteRule ^ /blog [R=301]

It is a good idea to start out with a 302 temporary redirection and only change that to a 301 permanent redirection later, once you are certain everything is correctly set up. That prevents caching issues while trying things out...

This implementation will work likewise in the http servers host configuration or inside a distributed configuration file (".htaccess" file). Obviously the rewriting module needs to be loaded inside the http server and enabled in the http host. In case you use a distributed configuration file you need to take care that it's interpretation is enabled at all in the host configuration and that it is located in the host's DOCUMENT_ROOT folder.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using distributed configuration files (".htaccess"). Those distributed configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

You can do that in your routes

// web.php
Route::redirect('/', '/blog');
Route::redirect('/anything', '/blog');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM