Search code examples
.htaccessfile-iowildcarddirectory-structure

Is it possible to use wildcards in the .htaccess file for mass moves?


I am reworking my website, going to be renaming a lot of directories, and need a simple way to write my .htaccess redirects for all of those pages. I am hoping for a solution that does not include a very long list of files. My .htaccess file is huge as it is.


Solution

  • You can use mod_alias or mod_rewrite for your redirecting. mod_rewrite works with regular expressions and mod_alias can work on both regular expression and path prefixes.

    Here are some examples for when you want to rewrite /foo/… to /bar/…:

    # mod_alias
    # path prefix
    Redirect 301 /foo /bar
    # regular expression
    RedirectMatch 301 ^/foo/(.*) /bar/$1
    
    # mod_rewrite
    RewriteEngine on
    RewriteRule ^foo/(.*) /bar/$1 [L,R=301]
    

    Note that mod_alias and mod_rewrite have different requirements for their regular expressions patterns. mod_alias does always require the full URL path. But with mod_rewrite it depends on whether you use it in a .htaccess file or in the server configuration/virtual host section. In a .htaccess file, you need to write the pattern without the per-directory path prefix (in case of the document root just /, in case of /quux/ it’s /quux/).