Latest Blog Posts

Editing the OpenCart Homepage
29.09.2025 2665 3 44 min

Editing the OpenCart homepage, customizing H1 and Title text, displaying products and modu..

How to Uninstall Powered by OpenCart
03.09.2025 4134 3 20 min

Remove Powered by OpenCart and customize footer: edit template, use theme editor or OCMOD ..

How to remove modules in OpenCart
28.08.2025 2114 3 12 min

Step-by-step instructions for deleting modules in OpenCart 3 via the admin panel, manually..

Which hosting to choose for OpenCart
25.08.2025 1432 3 19 min

Find out which hosting to choose for an OpenCart online store. Requirements, selection cri..

Setting up the correct htaccess file in OpenCart

33007 8 7 min
Setting up the correct htaccess file in OpenCart

The .htaccess file is important in the operation of the entire online store, let’s look at it in detail and what it includes by default. Moreover, out of the box it contains a lot of unnecessary stuff. At the same time, let's go through the main directives of this file. The file has many comments, I will only list the working lines.

Out of the box, .htaccess in OpenCart contains a large amount of useless code. First of all, let's go through the main directives and file settings. The standard .htaccess for opencart contains a large number of explanations , I will only describe the working lines.

Options +FollowSymlinks

Allows you to upload files that are physically located outside the root directory, but to which there are shortcuts (symbolic link). Needed for mod_rewrite to work

Options –Indexes

Prohibition of listing an empty directory. A directory that does not contain a default file (for example, index.html) will not display content with a list of files. The visitor will receive an HTTP error 403 - access forbidden .

<FilesMatch "(?i)((\.tpl|.twig|\.ini|\.log|(?<!robots)\.txt))">
 Require all denied
</FilesMatch>

Prohibition of direct access to files with specified extensions, except robots.txt. The message is also commented out:

"For apache 2.2 and older, replace "Require all denied" with these two lines:" # Order deny,allow # Deny from everyone If you have Apache 2.4+, leave it as it is.

Can be replaced with an alternative post type.

<FilesMatch "\.(tpl|ini|log|txt)">
 Order deny,allow
 Deny from all
</FilesMatch>
<Files robots.txt>
 Allow from all
</Files>

mod_rewrite block

RewriteEngine On

Enabling the mod_rewrite module to modify SEO URLs.

RewriteBase /

Transformation area. In this case, the entire store. You can limit it to a directory if your site is installed in a directory, for example: RewriteBase /shop

RewriteRule ^sitemap.xml$ index.php?route=extension/feed/google_sitemap [L]

When accessing an XML sitemap using the URL site.com/sitemap.xml redirects to site.com/index.php?route=extension/feed/google_sitemap

That is, to a dynamic site map, which is generated by the standard OpenCart module.

RewriteRule ^googlebase.xml$ index.php?route=extension/feed/google_base [L]

It was assumed that the link site.com/googlebase.xml would redirect to site.com/index.php?route=extension/feed/google_base, that is, the controller from the file catalog\controller\extension\feed\google_base.php would be called This controller was supposed to work with the Google database, which is no longer relevant. This rule can be removed from .htaccess

RewriteRule ^system/download/(.*) index.php?route=error/not_found [L]RewriteRule ^system/storage/(.*) index.php?route=error/not_found [L]

When trying to get the contents of the system/download folder via the link site.com/system/download/… or site.com/system/download/… redirect to site.com/index.php?route=error/not_found where the index method of the catalog controller is called \controller\errorot_found.php displaying the message “page not found”. In OpenCart 2.3 (maybe in earlier versions) there is no download folder in the system, so this rule can be removed from .htaccess. In addition, the system folder has its own .htaccess file that limits access to its contents.

If the previous regular expressions from the RewriteRule directives did not match, execution continues.

RewriteCond %{REQUEST_FILENAME} !-f

If the file specified in the request does not exist, then the check continues and the line with the RewriteRule directive may be executed. If index.php is present, then the check failed, the RewriteRule directive will not be executed, and the index.php file will eventually be loaded with all get parameters (if any).

RewriteCond %{REQUEST_FILENAME} !-d

If the requested directory (folder) does not exist

RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)

If the requested file is not a file with one of the specified extensions

RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

Then any request is redirected to site.com/index.php?_route_[after the _route_ parameter, what was requested is substituted - any line specified in the URL after the domain]

GET parameters, using a regular expression, are substituted in the string instead of “$1”

This directive will be executed if the index.php file was not specified in the URL, which also happens when URL CNC is enabled. During the application download process, it is checked whether CNC has been enabled in the settings. If not, then when the _route_ parameter is received, the 'common/home' controller will be called, which will display the home (main) page. If the CNC was enabled, the ControllerStartupSeoPro controller is executed from the catalog\controller\startup\seo_pro.php file or another selected one, where the _route_ parameter will be parsed into parts and aliases will be found from the url_alias database table based on the elements passed in the GET request, which will indicate to the script path to the controller/method that needs to be called to render the page.

Next are additional settings that may be needed in specific situations.

Total settings of the .htaccess file for OpenCart 2+ with comments:

#1. To use URL Alias, you need to run apache with mod_rewrite enabled.

#2. In your opencart directory, rename htaccess.txt to .htaccess.

# For any support issues, please visit: https://www.opencart.com/

Options +FollowSymlinks

# Prohibit listing an empty directory
Options -Indexes

# Deny direct access to files
&lt;FilesMatch "(?i)((\.tpl|.twig|\.ini|\.log|(?&lt;!robots)\.txt))"&gt;
 Require all denied
## For apache 2.2 and older, replace "Require all denied" with these two lines :
# Order deny,allow
# Deny from everyone
&lt;/FilesMatch&gt;

# SEO URL Settings
RewriteEngine On

RewriteBase /
# If your opencart installation is not installed in the main directory, make sure that it works in your folder, i.e. /becomes /shop/

# Redirect from www to ssl without www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Redirect from ssl without www to ssl
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING} ^(.+)/$
RewriteRule ^(.*)/$ /$1/?%1 [R=301,L]

RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=extension/feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=extension/feed/google_base [L]
RewriteRule ^system/storage/(.*) index.php?route=error/not_found [L]
RewriteRule ^system/download/(.*) index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

### Additional settings that may be required for some servers
### Uncomment the commands by removing the # sign in front of it.
### If you receive an "Internal Server Error 500" after enabling any of the following settings, restore # as this means your host does not support the directive.

#1: If your cart only allows you to add one item at a time, it's possible that register_globals is enabled. This directive will help him:
# php_flag register_globals off

#2. If your cart has magic quotes enabled, this may help disable them:
# php_flag magic_quotes_gpc Off

#3. Set the maximum file upload size. Most hosts limit this and don't allow you to override it, but you can try
# php_value upload_max_filesize 999M

#4. Set the maximum size of data sent. Uncomment this line if you get errors when forms don't save all fields
# php_value post_max_size 999M

#5. Set the maximum time the script can take. Uncomment this line if you have a lot of products or get errors when forms don't save all fields
# php_value max_execution_time 200

#6. Set a maximum time to receive input. Uncomment this line if you have a lot of products or get errors when forms don't save all fields
# php_value max_input_time 200

#7. Disable open_basedir restrictions
# php_admin_value open_basedir none

Products related to this post

301 Redirect Manager
699 грн.499 грн.
The redirect manager will allow you to create 301 redirects on OpenCart in a simple and understandable way right from the site adm..
Automatic SEO URL generation (CNC)
699 грн.499 грн.
After filling in the field with the Title on the page for adding a product, category, manufacturer or article, a transliteration i..
Editing robots.txt
Free
Robots.txt editor - a module for editing robots.txt in OpenCart (ocStore) directly from the admin panel.If the file does not exist..
ChatGPT Consultant

Comments

Leave your comment or question
Здравствуйте, помогите пож-ста правильно настроить мой htaccess, в долгу не останусь)
Answer Admin

Напишите в telegram.

Огромное спасибо автору и крепкого здоровья! Мучился 4 дня, пока не нашел эту статью.
Подскажите, а на третьей версии OpenCart будет работать данный .htacces файл?
Answer Admin

Должен.

Ошибка Сайт выполнил переадресацию слишком много раз. Удалите файлы cookie. Ничего не помогает
Как сделать редирект на https в opencart 3 в файле htaccess?
Answer Admin

Чтобы настроить редирект с HTTP на HTTPS в OpenCart 3 строку

RewriteEngine On

и после нее добавьте строки

# Принудительный редирект на HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Как полностью закрыть доступ к сайту через .htaccess?
Answer Admin

На время проведения технических работ или перед запуском проекта вы можете выключить доступ для всех пользователей, кроме тех, кому вы явно разрешите вход.

Простой способ закрыть сайт для всех

Добавьте в файл .htaccess следующий код:

Require all denied

Этот вариант подходит для Apache 2.4 и выше. Он полностью отключает доступ ко всем страницам сайта. Если вы используете более старую версию Apache, используйте следующий код:

Order deny,allow
Deny from all

Как разрешить доступ только себе

Если вы хотите заблокировать сайт для всех, кроме себя (например, во время разработки), вы можете разрешить доступ только с вашего IP-адреса:

<RequireAll>
 Require ip 123.45.67.89
 Require all denied
</RequireAll>>

Замените 123.45.67.89 на свой текущий IP-адрес.

Благодарю!
Подходит ли описанный в статье .htaccess для OpenCart 4?
Answer Admin

Да, базовые директивы продолжают работать так же, потому что OpenCart 4 использует тот же механизм ЧПУ через mod_rewrite.

Основные строки вроде
- RewriteEngine On
- RewriteBase /
- правила для _route_

остались актуальными и в OC4, ведь логика обработки SEO‑URL практически не изменилась.

Write Comment

Popular