skip to Main Content

As far as I know, they are all the same.
But I wonder why people use the rex in the RewriteRule Pattern.

Does ^ have any performance benefits?

RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [R,L]

Does / have any performance benefits?

RewriteRule /(.*) https://%{SERVER_NAME}/$1 [R,L]

Does () have any benefits?

RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]

Thanks.

2

Answers


  1. Does ^ have any performance benefits?

    Yes, the regex will only apply to the begining of the url so it will be faster

    Does / have any performance benefits?

    Not really, it just matches a slash character

    Does () have any benefits?

    In regex the parenthesis create a group to capture substrings

    Login or Signup to reply.
  2. There are few more things to keep in mind here (in addition to the other answer):

    1. This rule, as it is (alone, without any other rewrites or conditions), should probably be written as

       Redirect / https://example.com/
      

      In this case, the rewrite engine will not be involved which might result in
      (probably negligible) performance benefit.

    2. If you have a reason to use %{SERVER_NAME}, keep in mind that %{SERVER_NAME} might have different value than you expect, if UseCanonicalName is set to a non-default value. %{HTTP_HOST} should be safer.

    3. Even if you have to use RewriteRules (or RewriteCond), there is no need to use regex to capture full request URI, it is already available in %{REQUEST_URI}, so this should be faster:

      RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
      
    4. Keep in mind that RewriteRule behaves differently when use used in .htaccess compared to .conf:

      In per-directory context (Directory or .htaccess), the Pattern is
      matched against only a partial path: the directory path where the rule
      is defined is stripped from the path before comparison – up to and
      including a trailing slash!. The removed prefix always ends with a
      slash, meaning the matching occurs against a string which never has a
      leading slash.

      Or to put it more clearly: in .htaccess, there is no leading /.( just a reminder: you should not use .htaccess at all if you have access to Apache configuration files)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search