We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

Accessing And Changing Craft CMS Htaccess

10 min read
Shape April 2022 HR 45

Struggling with Craft's confusing .htaccess file? This guide provides Craft users and developers with expert insights on locating, editing, customising, troubleshooting, and testing changes to the powerful .htaccess file. Learn how to safely access this hidden gem to unlock greater control over your Craft CMS site without touching core code.

The .htaccess file in Craft CMS handles URL rewriting, redirects, and security headers. It can be accessed via cPanel, FTP, SSH, or locally. Edit with care on a staging server, testing changes incrementally. Understand impacts and keep backups. Customize URLs, enable caching, add redirects, and tighten security by tweaking .htaccess.

Craft CMS .htaccess File

What is an .htaccess File?

An .htaccess file is a configuration file that web developers place in directories on Apache web servers to alter settings and customize site behavior without accessing the core server configuration files. The .htaccess filename allows Apache to recognize it as a configuration file. These files provide an easy method for tweaking sites without root access to the server.

The most common uses for .htaccess files are URL rewriting, setting up redirects, and implementing security protections. For example, they allow you to transform ugly query string URLs into clean SEO-friendly paths using rewrite rules. You can also easily create 301 redirects from old URLs to new ones right from the .htaccess file. In addition, security policies like HTTPS-only access can be enforced using security headers in .htaccess.

In summary, .htaccess files grant developers more control over their websites. They work together with Apache to add conveniences like pretty URLs, implement redirects, and tighten security through headers, all without touching the core server configuration.

Purpose of .htaccess in Craft CMS

The .htaccess file serves several key purposes in Craft CMS: enabling clean URLs, setting up redirects, and configuring security headers.

The URL rewriting rules within the file are essential for transforming Craft's ugly default query string URLs into clean human-readable paths without "index.php". This improves site SEO and usability. Simple redirect statements can also be added to painlessly redirect old URLs to new locations.

In addition, implementing security headers like HTTP Strict Transport Security (HSTS) in .htaccess enhances site security for visitors. Things like forcing HTTPS and preventing content sniffing attacks become possible.

In essence, the .htaccess file brings optimization, convenience and security to Craft CMS sites. The ability to tweak URL structure for SEO, easily set up redirects, and tighten security through headers is invaluable.

Key Sections of the Default Craft .htaccess File

The main sections in a default .htaccess file for a fresh Craft 3 installation are:

Rewrite Rules - This largest section contains all the URL rewriting logic to map request paths to index.php invisibly. This is what transforms Craft's ugly default URLs into clean public facing ones.

Redirects - Simple redirect statements live here for defining redirects from old URLs to new destinations. They are commonly used for SEO purposes.

Security Headers - Important security headers like HSTS and anti-content sniffing are set here to improve site security.

Other Custom Rules - This is a place for additional custom rewrite rules, access restrictions, or other directives. It keeps them separate.

Understanding the purpose of each section is helpful when modifying or troubleshooting the .htaccess file:

The Rewrite Rules handle Craft's URL structure. The Redirects implement 301s for SEO. Security Headers enforce policies like HTTPS. Other Custom Rules provide a space for addons.

Modifying the appropriate section for the desired effect is key.

In summary, the main sections of Craft's default .htaccess file control URLs, redirects, security, and custom configs - core functions for any CMS site.

Accessing and Editing .htaccess in Craft CMS

Locating the .htaccess File

In a default Craft CMS 3 installation, the .htaccess file is located in the craft/config/ folder at the root of the site.

There are a few different methods to access and locate the .htaccess file:

Via cPanel - cPanel's File Manager provides a simple way to navigate to the craft/config/ folder and open .htaccess. No FTP client or SSH access is needed.

Through FTP - Connect to the site via an FTP client like FileZilla. Navigate to the craft/config folder and open the .htaccess file.

Via SSH terminal - SSH into the server and use terminal commands like cd and ls to change directories and list files. Locate craft/config and open .htaccess.

On a local Craft development environment like MAMP or Vagrant, the .htaccess file can be found under the craft folder in the web root.

So in summary, the main methods for locating the default .htaccess file are:

  • cPanel File Manager

  • FTP client

  • SSH terminal

  • Direct file access on local

The exact location will be /path/to/craft/config/.htaccess. Keeping the /craft/config/ path in mind makes finding the file much easier.

Viewing and Editing Methods

There are several ways to open and modify Craft's .htaccess file:

cPanel File Editor - cPanel's built-in file manager has a file editor that allows in-browser editing of .htaccess. No downloads or FTP clients needed.

FTP Client - An FTP program like FileZilla can be used to directly edit .htaccess within the /craft/config/ folder. Include the ability to download, edit locally, and re-upload.

SSH Terminal - SSH into the server and use a terminal text editor like Nano to modify the file. Give a basic example of editing via terminal.

Local Text Editor - For local development environments, a text editor like Notepad++ or VS Code can be used to edit the file directly.

The pros and cons of each:

cPanel File Editor - Convenient, no extra tools needed. But lacks more advanced editing features.

FTP Client - More powerful editor options. But requires installing and learning an external program.

SSH Terminal - No special tools required, but terminal editing has a learning curve.

Local Text Editor - Full features, but only viable on local servers.

In summary, cPanel and FTP editors provide the best options on live servers. Local development benefits from text editors with more capabilities. Consider ease of use vs features when choosing an editing method.

Editing Best Practices

When modifying the .htaccess file, it's important to follow best practices:

  • Use a staging or development server - Test all changes on a staging environment first before modifying production.

  • Back up the original - Download a backup copy of the original .htaccess before editing, in case you need to revert back.

  • Make small incremental changes - Only make small, incremental edits rather than massive untested overhauls.

  • Test extensively - Test site functionality thoroughly with each iteration and change.

  • Understand the impact - Know what a change will do before applying it and how it will impact the site.

  • Document all edits - Keep a changelog of exactly what changes you made with comments in the file.

This minimizes the chances of introducing errors that could break the site:

Making bulk untested changes or editing on live can easily introduce bugs that take down the site by breaking rewrite rules, creating server conflicts or causing infinite redirect loops, for example.

So careful incremental changes, extensive testing, backups, and documentation are crucial when modifying .htaccess. Take a cautious measured approach, and always test on staging first before touching production.

Following best practices keeps potential .htaccess errors from becoming headaches and prevents wasted time troubleshooting a broken site. Patience and care goes a long way when editing this critical file.

Customizing .htaccess in Craft CMS

URL Rewriting

The .htaccess file can be used to implement custom URL rewriting rules in Craft CMS. This allows you to create pretty vanity URLs and other user-friendly structures.

Rewrite rules are added using the RewriteRule directive. For example:

RewriteRule ^contact-us/(.*) contact/index.php?page=$1 [L]

This would map /contact-us/directions to /contact/index.php?page=directions behind the scenes.

The regex pattern matches any request starting with /contact-us/ and captures the rest in $1. We then rewrite this to the actual Craft page URL, passing page=directions in the query string.


Additional examples include:

# Rewrite brand product URLs

RewriteRule ^brands/([^/]+)/([^/]+) store/product?brand=$1&product=$2 [L]


# Vanity URL for about page

RewriteRule ^about-us$ about/index [L]


So with some regex knowledge, custom rewrites are possible. Just be sure to test rigorously to avoid conflicts or issues.

Redirects

The .htaccess file can also be used to set up both temporary and permanent redirects in Craft:

# 301 Permanent Redirect

Redirect 301 /old-page.html /new-page


# 302 Temporary Redirect

Redirect 302 /old-thing /new-thing


For example, to change a blog URL structure:

# Redirect old blog URLs to new format

Redirect 301 /blog/post-slug /news/post-slug


Or when changing domains:

# Redirect old domain to new one

Redirect 301 / http://newdomain.com/


Be sure to use 301s for SEO purposes whenever possible. Test extensively to avoid redirect loops.

Other Customizations

Besides URLs and redirects, other common .htaccess customizations include:


Security Headers - Adding security headers like:

# Enforce HTTPS

Strict-Transport-Security: max-age=31536000; includeSubDomains


# Prevent content sniffing

X-Content-Type-Options: nosniff


Caching - Adding caching directives like:

# 1 Week cache expiry for static assets

<FilesMatch "\.(ico|pdf|jpg|jpeg|png|gif|js|css)$">

Header set Cache-Control "max-age=604800, public"

</FilesMatch>


Gzip - Enabling gzip compression:

# Compress responses

<IfModule mod_deflate.c>

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript

</IfModule>

The possibilities are vast. Just be cautious and test all customizations thoroughly first. Refer to Apache docs for more examples.

In summary, the .htaccess file offers a powerful way to customize and optimize a Craft CMS site without core code changes.

Testing and Troubleshooting .htaccess

Testing .htaccess Changes

Thoroughly testing all .htaccess changes on a staging server before deploying to production is crucial. This helps identify and fix any errors or conflicts before they impact real visitors. Taking an incremental approach is best - introduce one change at a time and rigorously validate the intended effect occurs and no new issues are introduced before moving on.

For example, when adding a new rewrite rule, comprehensively load test all site pages to ensure no conflicts or unexpected behaviors arise. Check the Apache and Craft logs for any generated warnings or failures. Address any problems on staging first before rolling out to live.

Methodically testing each iteration identifies bugs before they reach production where they can cause headaches. Don't take shortcuts - catch issues early via disciplined testing.

Debugging Common .htaccess Issues

Some common .htaccess errors include 500 server errors from syntax problems, endless redirect loops from faulty logic, sites going down from blocked files, and 404s from bad regex.

Strategically troubleshooting involves first reverting to a known good recent backup to restore normal functionality quickly. Review the Apache and Craft logs to identify any specifics around the failure. Search online for solutions tied to any explicit error message. Then incrementally reintroduce changes on staging to isolate the problem.

With structured triage, most issues can be pinpointed and resolved. Stay calm and tackle methodically.

Rolling Back Failed Changes

When modifying .htaccess, retaining backups is invaluable for easily reverting bad changes. Before editing, download the original file. If problems occur, restore the working version by overwriting via FTP or SSH.

For total accessibility issues, hosts may need to intervene and restore from their backups. Having a known good state to roll back to should always be the first move with major errors to swiftly get the site running again. Backups provide a failsafe when experiments go sideways.

So be sure to retain legacy versions before tinkering for an easy fix down the line. With cautious testing and backups, .htaccess mishaps can be reversed smoothly.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat