Forums / National / Russian / Разделы в поддомены

Kort
#1 2024-05-04 13:12

Уже не помню где спрашивал Kopusha, так что выкладываю здесь то, что раскопал у себя:

Идея: преобразовать разделы в поддомены. Ну в смысле не преобразовать, а перенаправить и сообразно и глобально переписать на сайте ссылки.

Шаг 1

Добавляем в папку system файл functions.custom.php следующего содержания:

<?php
/**
 * Custom functions library
 */

defined('COT_CODE') or die('Wrong URL');

$subdomain_areas = array('docs', 'tutorials', 'blog');

/**
 * Changes  to / for List URLS
 *
 * @param array $args Args passed over from cot_url
 * @return string
 */

function list_url_structure(&$args) {
	global $structure, $sys, $subdomain_areas;

	$catpath = explode('.', $structure['page'][$args['c']]['path']);
	$root_cat = array_shift($catpath);

	if (in_array($root_cat, $subdomain_areas)) {
		// Make the URL absolute and exclude root cat
		$subdomain = $root_cat;
		$path = implode('/', $catpath);
		$url = $sys['scheme'] . '://' . $subdomain . '.' . $sys['domain'] . '/' . $path;
	} else {
		$url = str_replace('.', '/', $structure['page'][$args['c']]['path']).'/';
	}
	unset($args['c']);
	unset($args['e']);
	return $url;
}

/**
 * Changes to / for Page URLS
 *
 * @param array $args Args passed over from cot_url
 * @return string
 */

function page_url_structure(&$args) {
	global $structure, $sys, $subdomain_areas;

	(empty($args['c'])) && $args['c'] = 'system';

	$catpath = explode('.', $structure['page'][$args['c']]['path']);
	$root_cat = array_shift($catpath);

	if (in_array($root_cat, $subdomain_areas)) {
		// Make the URL absolute and exclude root cat
		$subdomain = $root_cat;
		$path = implode('/', $catpath);
		(!empty($path)) && $path .= '/';
		$url = $sys['scheme'] . '://' . $subdomain . '.' . $sys['domain'] . '/' . $path;
} else {
		$url = str_replace('.', '/', $structure['page'][$args['c']]['path']).'/';
	}

	if ($args['id']) {
		$url .= $args['id'];
		unset($args['id']);
	} elseif ($args['al']) {
		$url .= rawurlencode($args['al']);
		unset($args['al']);
	}
	unset($args['c']);
	unset($args['e']);
	return $url;
}

Шаг 2

В папку /plugins/urleditor/presets/ закидываем файл subdomains.dat

page	m=*						page?m={$m}
page	c=system&al=*			{$al}{!$c}
page	c=all					page
page	c=*&al=*				{page_url_structure()}
page	c=*&id=*				{page_url_structure()}
page	c=*						{list_url_structure()}
tags	a=all&t=*		        {$_area}/{$t}{!$a}
tags	a=*&t=*			        {$_area}/{$a}/{$t}
tags	t=*			            {$_area}/{$t}
index	*						{$_path}
plug	e=*						{$e}
plug	*                       {$_path}
users	m=details&u=*			users/{cot_url_username()}
users	m=register				{$m}
users	m=profile				{$m}
users	m=passrecover			{$m}
login	*						{$_area}
message	*						{$_area}
admin	m=*						admin/{$m}
admin	*						{$_area}
rss		m=*&c=*					{$_area}/{$m}/{$c}
rss		m=*&id=*				{$_area}/{$m}/{$id}
rss		c=*						{$_area}/{$c}
rss		m=*						{$_area}/{$m}
*		c=*&al=*				{$_area}/{cot_url_catpath()}/{$al}
*		c=*&id=*				{$_area}/{cot_url_catpath()}/{$id}
*		c=*						{$_area}/{cot_url_catpath()}
*		al=*					{$_area}/{$al}
*		id=*					{$_area}/{$id}
*		*						{$_area}

Шаг 3

В config.php включаем подгрузку кастомных функций:

$cfg['customfuncs'] = true;

В настройках плагина URLeditor выбираем пресет subdomains

Шаг 4

После всей этой истории все ваши ссылки вида site.com/docs будут переписаны на docs.site.com

Но чтобы все заработало, необходимо (как я предупреждал) добавить в настройки домена A-записи вида

docs.site.com	A	3600	ВАШ_IP

И так для каждого раздела-поддомена. Иначе ожидаемо получим ошибку при открытии ссылки с поддоменом.

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

Что дальше?

Пока не сильно понятно. Сама идея с выносом чего-то на поддомен интересная. Например, если у вас "выстрелила" какая-то страница и тянет на себя тематический, но не совсем нужный трафик. Но то, что выше, ориентировано на разделы. Например, можно (возможно более корректно, но не совсем красиво) реализовать локализации на поддоменах en.site.com.

В любом случае, все утыкается в разворачивание еще одного сайта / сайтов на подомене. А дальше уже можно поиграться с общей базой и общими в ней таблицами. Пробуйте, кому интересно.

SED.by - создание сайтов, разработка плагинов и тем для Котонти
This post was edited by Kort (2024-05-05 14:22, 2 weeks ago)
Kopusha
#2 2024-05-05 21:24

Для чего мне надо будет - сайт турист.ком
И на нем бангкок.турист.ком пекин.турист.ком и тд. Что бы не городить как раз общие базы и таблицы - делать это все виртуально. То есть имеем турист.ком/бангкок но его прячем в 404 а оставляем бангкок.турист.ком

Kort
#3 2024-05-06 04:32

Только, наверно, не прячем в 404, а перенаправляем через 301?

SED.by - создание сайтов, разработка плагинов и тем для Котонти
Alex300
#4 2024-05-07 06:49

Хорошо бы это добавить сюда. Можно даже на русском, а в начале страницы добавить:

The page has not yet been translated into English. 
You can help with the translation...

А если еще и с переводом - вообще блеск )

Есть миры, не здесь, там, где небеса горят, и моря засыпают, и реки дремлют; люди сделаны из дыма, а города – из песен. Где-то опасность, где-то несправедливость, даже где-то остыл чай. Идем Эйс, у нас много работы!...
...Sorry for my english...
Бесплатные расширения для Cotonti: https://lily-software.com/free-scripts/
Kopusha
#5 2024-05-07 17:14

How turn page categories in to subdomains (make a virtual redirect from site.com/category to category.site.com)
1. Add the following content to the file functions.custom.php in the system folder:

<?php
/**
 * Custom functions library
 */

defined('COT_CODE') or die('Wrong URL');

$subdomain_areas = array('docs', 'tutorials', 'blog');

/**
 * Changes  to / for List URLS
 *
 * @param array $args Args passed over from cot_url
 * @return string
 */

function list_url_structure(&$args) {
	global $structure, $sys, $subdomain_areas;

	$catpath = explode('.', $structure['page'][$args['c']]['path']);
	$root_cat = array_shift($catpath);

	if (in_array($root_cat, $subdomain_areas)) {
		// Make the URL absolute and exclude root cat
		$subdomain = $root_cat;
		$path = implode('/', $catpath);
		$url = $sys['scheme'] . '://' . $subdomain . '.' . $sys['domain'] . '/' . $path;
	} else {
		$url = str_replace('.', '/', $structure['page'][$args['c']]['path']).'/';
	}
	unset($args['c']);
	unset($args['e']);
	return $url;
}

/**
 * Changes to / for Page URLS
 *
 * @param array $args Args passed over from cot_url
 * @return string
 */

function page_url_structure(&$args) {
	global $structure, $sys, $subdomain_areas;

	(empty($args['c'])) && $args['c'] = 'system';

	$catpath = explode('.', $structure['page'][$args['c']]['path']);
	$root_cat = array_shift($catpath);

	if (in_array($root_cat, $subdomain_areas)) {
		// Make the URL absolute and exclude root cat
		$subdomain = $root_cat;
		$path = implode('/', $catpath);
		(!empty($path)) && $path .= '/';
		$url = $sys['scheme'] . '://' . $subdomain . '.' . $sys['domain'] . '/' . $path;
} else {
		$url = str_replace('.', '/', $structure['page'][$args['c']]['path']).'/';
	}

	if ($args['id']) {
		$url .= $args['id'];
		unset($args['id']);
	} elseif ($args['al']) {
		$url .= rawurlencode($args['al']);
		unset($args['al']);
	}
	unset($args['c']);
	unset($args['e']);
	return $url;
}

2. Place the file subdomains.dat into the /plugins/urleditor/presets/ folder.

page	m=*						page?m={$m}
page	c=system&al=*			{$al}{!$c}
page	c=all					page
page	c=*&al=*				{page_url_structure()}
page	c=*&id=*				{page_url_structure()}
page	c=*						{list_url_structure()}
tags	a=all&t=*		        {$_area}/{$t}{!$a}
tags	a=*&t=*			        {$_area}/{$a}/{$t}
tags	t=*			            {$_area}/{$t}
index	*						{$_path}
plug	e=*						{$e}
plug	*                       {$_path}
users	m=details&u=*			users/{cot_url_username()}
users	m=register				{$m}
users	m=profile				{$m}
users	m=passrecover			{$m}
login	*						{$_area}
message	*						{$_area}
admin	m=*						admin/{$m}
admin	*						{$_area}
rss		m=*&c=*					{$_area}/{$m}/{$c}
rss		m=*&id=*				{$_area}/{$m}/{$id}
rss		c=*						{$_area}/{$c}
rss		m=*						{$_area}/{$m}
*		c=*&al=*				{$_area}/{cot_url_catpath()}/{$al}
*		c=*&id=*				{$_area}/{cot_url_catpath()}/{$id}
*		c=*						{$_area}/{cot_url_catpath()}
*		al=*					{$_area}/{$al}
*		id=*					{$_area}/{$id}
*		*						{$_area}

In the settings of the URLeditor plugin, choose the preset "subdomains".

3. Enable loading of custom functions in config.php:

$cfg['customfuncs'] = true;

After completing the above steps, all your links of the form site.com/docs will be rewritten to docs.site.com.

4. However, for everything to work, you need to add A-records to the domain settings like this:

docs.site.com    A    3600    YOUR_IP

Repeat this for each subdomain section. Otherwise, you will encounter an error when opening a link with a subdomain.

Kort
#6 2024-05-08 04:09

Да я и сам. How turn))

SED.by - создание сайтов, разработка плагинов и тем для Котонти