Apache redirect everything except ACME challenge requests EXAMPLE

This is an example VHOST that redirects all HTTP requests to HTTPS - except ACME challenges.
The reason for this post is to have something people can find when searching for such an example.

<VirtualHost *:80>
    ServerName _default_
    # make a directory just for challenge files
    DocumentRoot ~/some-local-unique-path/
    <location /.well-known/acme-challenge/>
        # do nothing
    </location>
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>
3 Likes

Sorry Rudy but that looks like a mix of nginx and Apache. Won't work

Oh, Happy Cake Day!

5 Likes

I'm open to any improvement.

3 Likes

Well, this isn't valid Apache. And, as a template a common addition is ServerAlias

That isn't valid Apache either. That's nginx code

There is no need to check HTTPS off in a VirtualHost for port 80. It will always be off.

I posted an alternate in the offline group for further discussion

5 Likes

OK, how about this:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    # Redirect to HTTPS, except for ACME challenge
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/\.well\-known/acme\-challenge/
    RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

</VirtualHost>
5 Likes

That is similar to my include file.

<IfModule mod_rewrite.c>
  RewriteEngine On
  # Exclude Let's Encrypt ACME from HTTPS redirect
  RewriteCond %{HTTPS} !=on
  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge
  RewriteRule ^/(.*) https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
</IfModule>

If I were to drop the extraneous HTTPS check as @MikeMcQ mentioned, it would likely continue to function as expected.

5 Likes

With Apache 2.4 or later you could use an IF statement:

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot ~/some-local-unique-path/
    <If "%{REQUEST_URI} !~ m#/\.well-known/acme-challenge/#">
        Redirect permanent / https://example.com/
    </If>
</VirtualHost>

Notes:

  1. Set your ServerName and ServerAlias appropriately
  2. Set DocumentRoot to an existing folder just for the ACME challenge file
  3. Set the domain name in the Redirect statement to your preferred name (from ServerName or ServerAlias)
  4. RewriteEngine on is not required when using just Redirect as in this example
4 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.