Next.Js Apache .htaccess configuration for static exportation

# Enables the URL rewriting engine.
RewriteEngine On

# Sets the base URL for the rewrite rules.
RewriteBase /

# Remove www from the URL (Important for SEO)
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [R=301,QSA,NC,L]

# Open index.html file in the directory
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*[^/])$ /$1/index.html [L]

ErrorDocument 404 /404.html

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php82” package as the default “PHP” programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php82 .php .php8 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

Explanation:

  • Enable the URL rewriting engine with RewriteEngine On. This directive activates the mod_rewrite module, allowing us to define rules for how URLs are processed.
  • Set the base URL with RewriteBase /, which serves as the foundation for our rewrite rules.
  • Remove the “www” from the URL, which is crucial for SEO. By using a rewrite condition (RewriteCond) to check if the host starts with “www,” Redirect users to the non-www version of the site. This will improves search engine rankings.
  • Setup allows us to serve an index.html file from directories. If a request matches a directory, the server will automatically look for an index.html file within it.
  • Specified a custom 404 error page with ErrorDocument 404 /404.html.
  • Finally, this configuration includes a section for handling PHP files, ensuring compatibility with the Apache server settings.

Leave a Comment

Scroll to Top