Is it possible to include individual files in htaccess for a redirect list?

There is a ton of things in my main htaccess file for my site to function properly. I added redirects for migrated pages. I do not have root access to the server and using .htaccess is my only option.

Is it possible to include separate files for redirects in a .htaccess file so that I can save them separately and write programmatically to additional files in which my redirects are stored?

Basically, I want to reference individual files from my .htaccess to manage rules dynamically, and also to create one long .htaccess file with several smaller files.

I also want to add on-the-fly forwarding rules as things are changing on my site.

+4
source share
2 answers

You can use RewriteMap http://httpd.apache.org/docs/2.3/rewrite/rewritemap.html

Let's say your map file looks like this and is called move.map: -

/about profile /page/that/has/moved new/location 

You .htaccess will need something like this: -

 RewriteMap moved txt:moved.map RewriteCond %{REQUEST_URI} ^(.*)$ RewriteCond ${moved:%1|NOT_PRESENT} !NOT_PRESENT [NC] RewriteRule .? ${moved:%1} [NC,R=301] 

This will be redirected with status code 301 http://your.domain.com/about to http://your.domain.com/profile and redirect http://your.domain.com/page/that/has/moved to http://your.domain.com/new/location

Then you can programmatically create move.map.

I hope this helps.

+4
source

If you use .htaccess , then do not worry with RewriteMap - it is used only if you have root access to the server configuration or vhost, which is never the case when purchasing a general service offer.

If you are restricted in using .htaccess , you have two options:

  • First, you need to do what some packages do and make your application rewrite the .htaccess file based on the map you rewritten. The best way to do this is to have "bookrands" in your .htaccess file, for example.

     ##++AUTOMATIC rewrite rules <rules inserted by your app> ##--AUTOMATIC rewrite rules 

    And when the update happens, your application will read in .htaccess , replace the section between ## (++ | -) AUTOMATIC rewriting rules, write it back to a temporary file, then move the temp file to .htaccess (this makes the atoms of the rewrtie-back atom to * nix OS).

  • The second, which may work if you know a regular regex pattern that covers rewrites (this often happens), use the rule to match them with a script redirector that searches for a new target and produces a:

     $server = $_SERVER['HTTP_HOST']; header( "Location: http://$server/$newTarget?$parameters", TRUE, 301 ); 

    Note the 301 redirect, which means client browsers should cache this and keep that in mind in the future.

-one
source

Source: https://habr.com/ru/post/1398211/


All Articles