如何在httpd:alpine镜像中添加mod_rewrite并配置自定义.htaccess
Hey there! No worries at all about being new to Alpine Linux or Docker—we all start somewhere, and your goals are totally straightforward to achieve. Let's break down exactly what you need to do with your Dockerfile.
Step 1: Enable mod_rewrite
The httpd:alpine image comes with mod_rewrite pre-included, but it’s commented out in the default httpd.conf file. We’ll use sed to uncomment that line:
RUN sed -i '/LoadModule rewrite_module/s/^#//g' /usr/local/apache2/conf/httpd.conf
This command finds the line starting with #LoadModule rewrite_module and removes the leading comment character to activate the module.
Step 2: Allow .htaccess to Take Effect
By default, Apache ignores .htaccess files because the AllowOverride directive is set to None for the DocumentRoot. We need to update this to All so your custom rules work:
RUN sed -i '/<Directory "\/usr\/local\/apache2\/htdocs">/,/<\/Directory>/s/AllowOverride None/AllowOverride All/' /usr/local/apache2/conf/httpd.conf
This targets the <Directory> block for your default DocumentRoot and replaces the restrictive AllowOverride None with AllowOverride All.
Step 3: Copy Your Custom .htaccess
Finally, copy your local .htaccess file into the container’s DocumentRoot (which defaults to /usr/local/apache2/htdocs):
COPY .htaccess /usr/local/apache2/htdocs/
Full Dockerfile Example
Putting it all together, your complete Dockerfile will look like this:
FROM httpd:alpine # Enable mod_rewrite module RUN sed -i '/LoadModule rewrite_module/s/^#//g' /usr/local/apache2/conf/httpd.conf # Allow .htaccess overrides in DocumentRoot RUN sed -i '/<Directory "\/usr\/local\/apache2\/htdocs">/,/<\/Directory>/s/AllowOverride None/AllowOverride All/' /usr/local/apache2/conf/httpd.conf # Copy custom .htaccess to DocumentRoot COPY .htaccess /usr/local/apache2/htdocs/
Quick Testing Tips
- Build your image:
docker build -t my-custom-httpd . - Run a container:
docker run -p 8080:80 my-custom-httpd - Verify mod_rewrite is enabled: Exec into the container with
docker exec -it <container-id> ash, then runhttpd -M | grep rewrite—you should seerewrite_module (shared)in the output. - Test your .htaccess rules: Visit
http://localhost:8080and check if your rewrite rules behave as expected.
内容的提问来源于stack exchange,提问作者Archivar

