What is the role of .htaccess file in WordPress?

The .htaccess file is not actually required for WordPress to “work”. However, it is required if you wish to create a more user-friendly URL structure (ie. anything other than “plain” permalinks, as Jack suggests).

This is also why the default WordPress .htaccess file surrounds the directives in an <IfModule mod_rewrite.c> container. It “works” if “mod_rewrite” is not available on the system (you just get a less user-friendly permalink structure). mod_rewrite is Apache’s URL rewriting module.

The .htaccess file itself is a “per-directory Apache configuration file”. To a limited extent (stress limited) it can be used to configure the Apache server environment. However, it is mostly used to configure/help the web application (in this case WordPress). Using .htaccess you can redirect/rewrite the URL, configure client-side caching, restrict access, etc. Although most of this can be configured through a more friendly WordPress plugin. .htaccess syntax can appear a bit cryptic and it is unforgiving if you get it wrong.

The default WordPress .htaccess file implements a “front-controller” pattern. It uses mod_rewrite to route all requests (for files that don’t exist, ie. virtual URLs) through index.php. This enables WordPress to then examine the requested URL, construct the page and return this to the client.

Just as additional side note… if you later wanted to add some redirects to this file (in the form of RewriteRule directives) then these must go before the WordPress front-controller. If you put them at the end of the file they will unlikely be processed. This is a surprisingly common source of error. If, for instance, you used cPanel to create some external redirects, then cPanel will create these at the end of the .htaccess file, so would require some manual editing.

The .htaccess file is usually located in the root directory of the WordPress installation. However, it can be moved to parent directories (even above the document root) if you know what you are doing. .htaccess files are “per-directory”. Directives in the .htaccess file in the root influence that directory and all subdirectories. If you had another .htaccess in a subdirectory then these directives override the parent .htaccess file. If you have access to the main server config then you don’t need .htaccess at all.