No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
MVC-L: controllers, models, templates

seo_url in OpenCart: how the SEO URL table and the startup/seo_url controller work

How OpenCart 3.0 and 4.1 store SEO URLs in the seo_url table, parse the address in startup/seo_url, and build links via rewrite().

12 min read OC 3.0 OC 4.1

SEO URLs in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → rely on two things: the seo_url table with links between a "keyword" and "query parameters", and the startup controllerCode that receives a request and prepares data. More in the glossary → startup/seo_url. On an incoming request, this controller converts /noutbuky/macbook-pro into regular GET parameters. When the store generates a link, the same controller performs the reverse conversionThe share of visitors who completed a goal, usually a purchase. Calculated as orders ÷ visits × 100%. More in the glossary → through the rewrite() method. If you understand how seo_url works in OpenCart internally, you can explain any 404 on a "pretty" address or any ?route=… tail in a link.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

What does the seo_url table store in 3.0 and 4.1?

The oc_seo_url table (the prefix depends on the installation) stores the correspondence between a keyword in the address and the parameter it replaces. Each row is tied to a store (store_id) and a language (language_id), so a single product in a multilingual store has several rows, one per language. The structure differs significantly between versions, and this is visible directly in the controller code: in 3.0 it reads the query field, while in 4.1 it works with the key, value, and sort_order fields.

AspectOpenCart 3.0OpenCart 4.1
What is replacedA row query of the form product_id=42The pair key + value, for example product_id and 42
Keywordkeywordkeyword
Order of segments in the pathDetermined by the order of parameters in the link's query string (for example, path before product_id); there is no separate sort fieldThe sort_order field
Parameters supported "out of the box"product_id, path, manufacturer_id, information_idAny GET parameter that has a row

Examples of records for each version:

-- OpenCart 3.0: виробник Apple для магазину 0, мова 1
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `query`, `keyword`)
VALUES (0, 1, 'manufacturer_id=8', 'apple');

-- OpenCart 4.1: сторінка контактів як окремий маршрут
INSERT INTO `oc_seo_url` (`store_id`, `language_id`, `key`, `value`, `keyword`, `sort_order`)
VALUES (0, 1, 'route', 'information/contact', 'kontakty', 0);

You can edit these records manually in "Design → SEO URL" (Design → SEO URL). For products, categories, manufacturers, and information pages, it is more convenient to fill them in on the "SEO" tab of the entity's form.

Список SEO URL: ключ, значення, ключове слово, магазин і мова
SEO URL list: key, value, keyword, store, and language · OpenCart 4.1.0.4

How does a request reach the startup/seo_url controller?

The web server passes PHP not the "pretty" address, but index.php with the _route_ parameter. The distribution includes a file for this purpose: .htaccess.txt. It needs to be renamed to .htaccess, and then the mod_rewrite rule will convert /noutbuky/macbook-pro into index.php?_route_=noutbuky/macbook-pro. Under Nginx, the same must be described manually:

location / {
    try_files $uri $uri/ @opencart;
}
location @opencart {
    rewrite ^/(.+)$ /index.php?_route_=$1 last;
}

Next, the request passes through the core (this path is described in detail in the article on framework.php and the request path). Before the main controller runs, the startup pre-actions are executed, and startup/seo_url is among them. Its task is to fill $this->request->get as if the user had opened a regular index.php?route=…&product_id=…. After that, the standard routing by the route= parameter takes over.

flowchart TD
  A["Browser: /noutbuky/macbook-pro"] --> B["Server: index.php?_route_=..."]
  B --> C["startup/seo_url: index()"]
  C --> D["Lookup of each segment in seo_url"]
  D --> E["Filling request->get"]
  E --> F["Router calls the controller from route"]
  F --> G["$this->url->link() in templates"]
  G --> H["rewrite(): parameters are converted to SEO URLs"]

The config_seo_url switch is turned on in "System → Settings" (System → Settings), on the "Server" tab (Server), in the option for using SEO URLs. There is an important difference between versions. OpenCart 3.0: parsing _route_ always runs, and the setting only affects whether rewrite() is connected to link generation. OpenCart 4.1: parsing and rewrite are both inside the config_seo_url check, so with the option disabled, "pretty" addresses are not recognized at all.

Вкладка «Сервер»: перемикач використання SEO URL
Server tab: the switch for using SEO URLs · OpenCart 4.1.0.4

How OpenCart 3.0 parses the address

In 3.0, the _route_ string is split by slashes, and the empty last segment (the trailing /) is discarded. Then a separate SQL query is executed for each segment:

catalog/controller/startup/seo_url.php · OpenCart 3.0.5.1 · lines 18–34

foreach ($parts as $part) {
	$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE keyword = '" . $this->db->escape($part) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "'");

	if ($query->num_rows) {
		$url = explode('=', $query->row['query']);

		if ($url[0] == 'product_id') {
			$this->request->get['product_id'] = $url[1];
		}

		if ($url[0] == 'category_id') {
			if (!isset($this->request->get['path'])) {
				$this->request->get['path'] = $url[1];
			} else {
				$this->request->get['path'] .= '_' . $url[1];
			}
		}

Several non-obvious things follow from this code:

  • The language is not taken into account during parsing. The filter applies only by keyword and store_id. If the Ukrainian and English versions have the same keyword, the first row found is used. For a product this is not a problem, because product_id is the same, but the page language will not switch as a result.
  • Categories are concatenated into path. The address /noutbuky/apple is converted into path=20_27. The order of segments in it matters.
  • An unknown segment immediately produces a 404:

catalog/controller/startup/seo_url.php · OpenCart 3.0.5.1 · lines 44–51

if ($query->row['query'] && $url[0] != 'information_id' && $url[0] != 'manufacturer_id' && $url[0] != 'category_id' && $url[0] != 'product_id') {
	$this->request->get['route'] = $query->row['query'];
}
} else {
$this->request->get['route'] = 'error/not_found';

break;
}

The first line of this fragment explains how route addresses work in 3.0: if query does not contain one of the four known parameters, the entire value becomes route. So the query = 'information/contact', keyword = 'kontakty' row will open the contacts page at the address /kontakty. But the blog_id=5 row will break, because route becomes equal to blog_id=5. When no route is set, the controller substitutes it itself based on the parameter found: product/product, product/category, product/manufacturer/info, or information/information.

What changed in OpenCart 4.1?

In 4.1, the controller became universal. It no longer knows about products and categories; it simply converts each found row into a "key = value" pair in GET:

catalog/controller/startup/seo_url.php · OpenCart 4.1.0.4 · lines 35–51

foreach ($parts as $key => $value) {
	$seo_url_info = $this->model_design_seo_url->getSeoUrlByKeyword($value);

	if ($seo_url_info) {
		$this->request->get[$seo_url_info['key']] = html_entity_decode($seo_url_info['value'], ENT_QUOTES, 'UTF-8');

		unset($parts[$key]);
	}
}

if (!isset($this->request->get['route'])) {
	$this->request->get['route'] = $this->config->get('action_default');
}

if ($parts) {
	$this->request->get['route'] = $this->config->get('action_error');
}

What matters here for the developer:

  • The SQL has been moved into the catalog/model/design/seo_url.php model, method getSeoUrlByKeyword(). Overriding the behavior is now more convenient through events on the model rather than by editing the controller. For more about models, see the article about models and $this->db.
  • The key can be anything: route, product_id, path, language, or a parameter of your module. Therefore, custom SEO URLs in 4.1 are added without any core modifications.
  • The loop does not stop at the first unknown segment. It goes through all of them, and then, if anything remains unrecognized, sets action_error. The effect is the same (404), but third-party code that cleans up $parts works more predictably in this scheme.
  • Without route, action_default is substituted from the core config (usually the home page). The article about config.php and system/config explains where such values come from.

Look at categories separately. In 4.1, path is stored as a regular value, without concatenation. If the address contains two categoryA section of the catalog that contains products. It may have subcategories. More in the glossary → segments, the second will simply overwrite the first. Therefore, the row for a nested category must contain the full path in value (for example 20_27).

You do not form SEO addresses manually. Controllers call $this->url->link('product/product', 'product_id=42'), and the URL class (system/library/url.php) passes the result through all registered rewrite objects. startup/seo_url adds itself there by calling $this->url->addRewrite($this), so its rewrite($link) method receives the finished link with the query string.

OpenCart 3.0: a whitelist of parameters

Rewrite in 3.0 handles only product_id (for product/product), manufacturer_id, information_id, and path. Unlike parsing, here there is a filter by language_id, so links are generated in the language of the current page. There is a trap associated with path: if even one category in the chain has no keyword, the accumulated $url is reset along with the segments added earlier, and path is still discarded from the parameters. The method returns the original link with index.php?route=… only when no other parameter then yields a keyword. Otherwise, you get an SEO URL without category segments, for example only the product keyword, if product_id appears in the link after path. The route parameter is not rewritten at all, so even with the information/contact row in the table, the contacts link will remain "ugly", although the address /kontakty will still open.

OpenCart 4.1: each pair is looked up in the table

catalog/controller/startup/seo_url.php · OpenCart 4.1.0.4 · lines 116–126

$index = $key . '=' . $value;

if (!isset($this->data[$language_id][$index])) {
	$this->data[$language_id][$index] = $this->model_design_seo_url->getSeoUrlByKeyValue((string)$key, (string)$value);
}

if ($this->data[$language_id][$index]) {
	$paths[] = $this->data[$language_id][$index];

	unset($query[$key]);
}

Each pair from the query string is looked up through getSeoUrlByKeyValue(), and the result is cached in the $data property within a single request. This matters because on a category page, dozens of links share the same route=… and language=…. The found segments are sorted by sort_order, and whatever is missing from the table remains in the query string. This gives the diagnostic rule: if you see /macbook-pro?route=product/product in 4.1, the table lacks a row for the pair route / product/product in the current language and store.

How to add an SEO URL for your own module

A typical task looks like this: a blog module has an article page with a route and its own parameter, and it needs to be served at a human-readable address.

OpenCart 4.1

  1. When installing the module, add a row for the route: key = 'route', value = the full route of your controller (in 4.1 this is the path with extension/…), keyword = 'blog'.
  2. When saving an article in the admin, write a row key = 'article_id', value = '5' for each language and each store.
  3. Set sort_order so that the route comes before the article. Then the address will look like /blog/moya-stattia.
  4. When deleting an article or uninstalling the module, remove your rows so that "orphans" do not accumulate in the table.
// Приклад: збереження SEO-ключів статті в адмін-моделі модуля (4.1)
$this->db->query("DELETE FROM `" . DB_PREFIX . "seo_url` WHERE `key` = 'article_id' AND `value` = '" . (int)$article_id . "'");

foreach ($data['article_seo_url'] as $store_id => $languages) {
	foreach ($languages as $language_id => $keyword) {
		if ($keyword) {
			$this->db->query("INSERT INTO `" . DB_PREFIX . "seo_url` SET `store_id` = '" . (int)$store_id . "', `language_id` = '" . (int)$language_id . "', `key` = 'article_id', `value` = '" . (int)$article_id . "', `keyword` = '" . $this->db->escape($keyword) . "', `sort_order` = '1'");
		}
	}
}

Nothing needs to be changed either in startup/seo_url or in the page controller (how the controller is structured): it will receive article_id in $this->request->get, as if it came as a regular GET parameter.

OpenCart 3.0

The standard mechanism is not enough here. Parsing will turn article_id=5 into a broken route, and rewrite will ignore your parameter. There are two working approaches. The first: an OCMOD modification of catalog/controller/startup/seo_url.php that adds your key to the parsing branches and to the rewrite() whitelist. The second: a custom startup controller that registers another rewrite object through $this->url->addRewrite() and parses its own segments. Keywords in the table must be unique within a store. Otherwise, due to the absence of a language filter during parsing, you will get unpredictable results.

Why does an SEO URL return 404 or not get generated: diagnostics

Most SEO URL problems come down to a few causes. Check them in this order:

  • Does _route_ arrive? Temporarily output $this->request->get in the controller. If there is no _route_ there, the problem is at the server level: the file .htaccess was not renamed, AllowOverride is disabled, the rule is missing in Nginx, or it was installed in a subdirectory without editing RewriteBase.
  • Is config_seo_url enabled? In 4.1, without it, parsing does not happen at all.
  • Do store_id and language_id match? After adding a language or a second store, old products have no rows for the new combinations. Links for them are generated without SEO URLs.
  • Are all categories in the chain filled in? In 3.0, one category without a keyword "breaks" the path for all of its descendants.
  • Are there no duplicates? The same keyword for two entities in one store produces a random parsing result: "the wrong product opens".
Вкладка «SEO» у формі товару: ключове слово для кожного магазину й мови
"SEO" tab in the product form: a keyword for each store and language · OpenCart 4.1.0.4

Filling in missing keywords in bulk after a catalog import is inconvenient by hand. There are generators of transliterated SEO URLs for this, for example SEO URL Generator PRO, but you can also do the same with your own script based on the table scheme described above. Language prefixes and hreflangA hint to search engines about the language versions of a page. More in the glossary → on top of this mechanism are covered in a separate article about multilingual support and URL prefixes.

If your store runs on OpenCart 3.0 and you would rather not maintain your own startup/seo_url modifications, we recommend our module OCT SEO PRO. It brings SEO URLs, redirects, and the sitemap together in one place. Keywords, redirects from old addresses after they change, and the site map are conveniently configured from the admin, and you do not have to edit the seo_url table by hand.

Summary

  • The seo_url table links a keyword to a query parameter. In 3.0 this is the query field; in 4.1 it is the key/value pair plus sort_order.
  • startup/seo_url works in both directions: index() parses _route_ into GET parameters, and rewrite() converts links with $this->url->link() into SEO URLs.
  • OpenCart 3.0 knows only four entity types and does not filter by language during parsing. Custom pages will require a modification or your own rewrite.
  • OpenCart 4.1 is universal: for a module to receive an SEO URL, correct rows in the table are enough.
  • A ?route=… tail or a 404 almost always means a missing row for a specific store/language pair or a problem with the server rule.

Next, it is worth looking at what happens after the address is parsed: how the router finds the controller by route= and how admin and catalog work on one core (the admin does not use SEO URLs). The remaining topics about controllers, models, and templates are collected in the section MVC-L: controllers, models, templates.

FAQ

Can OpenCart use the same keyword for different languages?
In 4.1 it depends on how the model looks up a row by keyword, so it's safer to keep keywords unique within the store. In 3.0 parsing ignores the language, so a duplicate will lead to the first matching row being selected.
Does the number of rows in seo_url affect performance?
Each URL segment and each link on the page makes a query to the table, so an index on keyword and on query or key/value matters. In 4.1 rewrite results are cached within a single request; in 3.0 there is no such cache.
Why don't links in the admin become SEO URLs?
The seo_url startup controller is loaded only in the catalog; the admin works with index.php?route=… and user_token. This is by design and doesn't affect SEO.
How do I set up a 301 redirect from the old URL after changing a keyword?
OpenCart core doesn't keep old keywords, so after a change the old address will return 404. Redirects are set up with server rules, a custom startup controller, or an SEO module with a redirect table.
Do I need to clear the cache after manually changing the seo_url table?
The standard controller reads the table directly, so changes take effect immediately. The exceptions are third-party modules that cache SEO URLs in the file cache, and a full page cache on the server.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.