.htaccess geolocation without mod_geoip - .htaccess

I'm trying to figure out a method to do the following:
Include a "lang token" into ALL .htaccess rewrited-urls, like this:
RewriteRule ^/?$ _main_htaccess_handler?mod=homepage&lang=[LANG_STRING]
RewriteRule ^disclaimer\.htm?$ _main_htaccess_handler?mod=disclaimer&lang=[LANG_STRING]
... and so on, for all the urls
All countries EXCEPT Italy:
[LANG_STRING] = 'EN';
Country ITALY
[LANG_STRING] = 'IT';
Now, searching for a method to accomplish this, I've found this script:
http://ipinfodb.com/country_query.php?country=IT&output=htaccess_allow
This will output a list of IPs allocated to a country, with a 99.5% accuracy.
I would like to "link" those IP subnet strings to the .htaccess type of approach mentioned above.
Anyway, I'm a little bit confused about geolocalization via .htaccess without the mod_geoip.
Do you think the solution I've "created" and mentioned above can work good? And then, what about search engines? Will, for example, Google Italy correctly find pages in Italian? (this question applies to all search engines)
Thank you very much

Having a huge .htaccess file is never a good idea, since the file is parsed before every request to the given website, resulting in loss of performance.

After having tried some techniques, I've opted for an hybrid one: PHP + htaccess
I'm writing it for the ones that will fly into this question.
HTACCESS CONFIGURATION:
RewriteRule ^/?$ _builder.php?mod=language-redirect [L,QSA]
RewriteRule ^en/?$ _builder.php?mod=homepage&lang=en [L,QSA]
RewriteRule ^it/?$ _builder.php?mod=homepage&lang=it [L,QSA]
_builder.php CODE ( relative to Italian and English Language, easily convertible to suit your needs )
if ( ! isset ( $_GET['lang'] ) || ( $_GET['lang'] != 'en' && $_GET['lang'] != 'it' ) ) {
// reaches here when someone accesses the / of the site. This piece of code outputs the correct geolocation language. If needed, you can also place an header redirect to the correct language-based homepage instead of defining the language
$geoplugin = new geoPlugin();
if ( $geoplugin -> countryCode == 'IT' ) define ( 'LANGUAGE', 'it' );
else define ( 'LANGUAGE', 'en' );
}
else {
if ( $_GET['lang'] == 'it' ) define ( 'LANGUAGE', 'it' );
else define ( 'LANGUAGE', 'en' );
}
Finally, the geoPlugin Class is reachable through Google "PHP geoplugin" or by this url:
http://www.geoplugin.com/webservices/php
Remember to place the language setter snippet into your main builder, so the script can know what language to output on the page, even if that wasn't passed by htaccess.

Related

Liferay friendly url with optional param

My URL have some params, so i use friendly URLs to solve that ugly URL liferays generates by default.
couple of this params sometimes are empty, that mean its no needed, but other times give me some ID i use for a query.
Example param not null:
https://myliferay.com/example-portlet/-/example-portlet/search/idTable-7
//it works
Example null param:
https://myliferay.com/example-portlet/-/example-portlet/search/idTable-null
//it works
With null param it works, but i dont like to see a null on my URL.
I want something like "":
https://myliferay.com/example-portlet/-/example-portlet/search/idTable-
//Doesnt work
But it doesnt work, its like the URL doesnt match the friendly URL pattern when a param its empty.
<route>
<pattern>/search/idTable-{idTable}</pattern>
<generated-parameter name="idTable">{idTable}</generated-parameter>
<implicit-parameter name="p_p_lifecycle">0</implicit-parameter>
<!--more implicit params-->
</route>
How can i specify optionality of a parameter?
Its like all vars of friendly url use a regex. You can change/override this regex like this: {idTable:\d}
<route>
<pattern>/search/idTable-{idTable:.*}</pattern>
<generated-parameter name="idTable">{idTable}</generated-parameter>
<implicit-parameter name="p_p_lifecycle">0</implicit-parameter>
<!--more implicit params-->
</route>
i used .* as regex for 0 or more characters, but i dont know if it will bring me problems later. If anyone knows why is not a good idea to use that regex comment it please.
Upgraded the regex with \d* to search only digits or empty: {idTable:\d*}
Info: Making URLs friendlier 7.0

Prestashop Friendly URL's

I've been trying to create a second option of url rewrites to a product inside prestashop. In the standard Prestashop installation at the SEO & URL's section i've got the following products url build-up:
{category:/}{id}-{rewrite}-{ean13}.html
This creates the following products url:
https://www.example.com/{category-name}/{product-id}/{product-name}/{ean13}.html
What i would like to add is an option for various reasons to acces a products page through the following url build up:
ean/{ean13}.html
The result url would be something like the following example:
https://www.example.com/ean13/{ean13}.html
NOTE, ID is a standard required field of the url build up, this means that i can't use: "Just ajust the url build up" as an answer.
Is there a module, addon, or piece of code out there that would be able to generate these kind of structures?
I did find some "Remove ID's from pretty url's" modules but that doesn't give me the result i'm searching for. Only partially since it only removes the ID's.
It wouldn't be a problem if it's a redirect to the standard url build up as mentioned in the first {code} segment. I know i could write rewrite rules in my .htacces file but to do this for every product would be a lot of work so i was wondering if there is a more easy way of achieving this.
As always thanks in advance!
If you're fine with redirect to standard URL then the solution is quite easy with a module.
Create a module that uses hook moduleRoutes and configure a friendly URL to use module controller
Create a module front controller
Run a db query in your custom controller to check if a product with requested EAN exists
Redirect to product page if product exists, otherwise to 404 page or something
I assume you know how to write modules and controllers, so I won't write entire code just the relevant bits.
Hook moduleRoutes in module class.
In this hook you can configure a friendly URL for your custom controller.
public function hookModuleRoutes()
{
return [
'mymodulename-mycontrollername-root' => [
'rule' => 'ean13/{:ean13}.html',
'controller' => 'mycontrollername',
'keywords' => [
'ean13' => ['regexp' => '[0-9]+', 'param' => 'ean13']
],
'params' => [
'fc' => 'module',
'module' => 'mymodulename'
]
]
];
}
So visiting https://www.example.com/ean13/12345.html will run your module controller and a GET variable ean13 will have a value of 12345.
Then create mycontrollername module controller where you can use postProcess() method to check if EAN exists.
public function postProcess()
{
$query = new DbQuery();
$query->select('id_product')
->from('product_attribute', 'pa')
->where('pa.ean13 = ' . (int)Tools::getValue('ean13'))
$productId = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($query);
if ($productId) {
Tools::redirect($this->context->link->getProductLink($productId));
}
Tools::redirect('pagenotfound');
}
In query we check in product_attribute table as product combinations can have their own EAN13 and you also want those EAN13's to redirect to product page.
The basics of this answer is most commonly used to replace core product search controller with a custom and SEO friendly one.

Yii2 Trailing Slashes in URL is breaking the route

I configured UrlManager in a project and It was working the way I wanted.
Now i tried to add a content whose name contains a trailing slash but i get an error 404 (Object not found).
For example:
www.test.com/article/detail/id_of_article/title_of_article
title_of_article = People are ... => Work
title_of_article = 1/3 of People are ... => Doesn't Work (Object not Found)
The Trailing Slash is breaking the Url although it is encoded in %2F
This is how i create url:
Html::a(Html::encode($model->title),
['article/detail', 'id' => $model->id, 'title' => $model->title])
I don't really know how I can deal with that.
For This , the best solution is to use slug names.
Instead of id and title, take one more field called slug_name in your database.
On Add or update of any record generate slug name and store in db.
For generating slug name, you can use custom function as below.
public function getSlugName($id,$title)
{
$slug=$id;
if(isset($title) && $title!=null)
{
// remove all spacea
$slug.='-'.str_replace(' ','-',strtolower($title));
}
$slug=preg_replace('/[^A-Za-z0-9\-]/', '', $slug); // Removes special chars.
$slug=str_replace(array('--'), '-', $slug); // remove multiple --
return $slug;
}
This function will return you uniq name. So you can use it in url.
This is also help in SEO.
Could be you need URL normalization
Since version 2.0.10 UrlManager can be configured to use UrlNormalizer
for dealing with variations of the same URL, for example with and
without a trailing slash.
NB by default UrlManager::$normalizer is disabled. You need to explicitly configure it in order to enable URL normalization.
see how here http://www.yiiframework.com/doc-2.0/guide-runtime-routing.html#url-normalization
There is an encodeParams property of UrlRule. Please try with that.

How to use add_rewrite_rule function, while permalink structure is disabled?

I am using the add_rewrite_rule() function to modify my URL structure.
I'm wanting to use add_rewrite_rule to add a custom rule but these rules only get added in when other than default settings are selected in my permalink settings area.
i.e. in the settings there are following options:
- Default http://localhost/wordpress/?p=123
- Day and name http://localhost/wordpress/2014/08/14/sample-post/
- Month and name http://localhost/wordpress/2014/08/sample-post/
- Numeric http://localhost/wordpress/archives/123
- Post name http://localhost/wordpress/sample-post/
- Custom Structure http://localhost/wordpress
So, when I select other then 'Default', my add_rewrite_rule() function works, but while selecting 'Default', the function doesn't seem to be work. So please suggest me how to work the function in any condition. Any help would be Appriciated.
Update:
I think the problem lies here:
When I use this, while selecting 'Default':
get_option('permalink_structure');
I got nothing.
While in the other cases, there are some values like:
/%postname%/
/archives/%post_id%
/%year%/%monthnum%/%postname%/
The Default permalinks, or so called "Ugly" permalinks, are not adding anything to the .htaccess file, so the Apache rewrite engine is not enabled. Without the rewrite engine, no rewrites can be done. So the short answer is that rewrites are not possible with Default permalinks.
I can recommend you to use rewrites along with query vars. When adding a rewrite rule, pass your custom data to a query var, and build the functionality around that query var. This way your functionality will work in all situations and with all permalink types.
So for example if you have the following rule:
add_rewrite_rule('^sometest/([^/]*)/?','index.php?custom_query_var=$matches[1]', 'top');
and you have the custom_query_var added as a query var by using the following code:
function add_query_vars_filter( $vars ){
$vars[] = "custom_query_var";
return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );
then when Default permalinks are selected, the following URL would work for you:
http://yoursite.com/index.php?custom_query_var=abc
and if "Pretty" permalinks are selected, the URL rewriting would work and your URL would look the following way:
http://yoursite.com/sometest/abc/
which is basically the best that can be achieved with rewrites.
I agree with #Martin. Here's a resource that will help https://core.trac.wordpress.org/ticket/15235
use this:
function my_add_query_vars( $qvars ) {
$qvars[] = 'business-coaching';
$qvars[] = 'country';
$qvars[] = 'territory';
$qvars[] = 'region';
return $qvars;
}
add_action('query_vars', 'my_add_query_vars');
//Write the rule
function add_analytic_rewrite_rule()
{
// Regex:The regex to match the incoming URL is:business-coaching(/([^/]+))?(/([^/]+))?(/([^/]+))?/?
// Redirect Rule :The resulting internal URL: `index.php` because we still use WordPress
// `pagename` or page_id=45 because we use this WordPress page
// `country` : we will assign the first captured regex part to this variable
// `territory` we will assign the second captured regex part to this variable
// `region` we will assign the third captured regex part to this variable
add_rewrite_rule('business-coaching(/([^/]+))?(/([^/]+))?(/([^/]+))?/?','index.php?page_id=45&country=$matches[2]&territory=$matches[`enter code `enter code here`here`4]&region=$matches[6]','top');//superfinal
}
add_action('init', 'add_analytic_rewrite_rule');

url rewriting : How to rewrite 2 urls with same number of parameters?

I've created some url rewriting rules.
It works fine.
But i have 2 pages with urls like that :
actualites.php?id=xxx& alias=xxx
--> Result : id-alias.php (ex : 1-article_name.php)
equipe.php?id=xxx& alias=xxx
--> Result : id-alias.php ((ex : 1-article_name.php)
These 2 pages are different, not the same design, etc.
I would like to rewrite these 2 different pages. My question is how to have two different rules for these 2 urls.
Since they have 2 parameters, i have only one rule applied (the first one)
#become : 1-alias.php
RewriteRule ^([0-9]*)-(.*)\.php$ actualites.php?cat=$1&alias=$2 [L]
#become : 1-alias.php
RewriteRule ^([0-9]*)-(.*)\.php$ equipe.php?id_equipe=$1&alias=$2 [L]
Unless you want to add code in actualites.php that first checks whether the parameter values for "cat" and "alias" are valid, then you can't.
If you want to code that into actualites.php, check if the parameters are valid, and if not, send the params to equipe.php as "id_equipe" and "alias". Otherwise you'll need to add something to the URL to validate which request you're actually mapping to. For example:
http://yourdomain.com/a/1-article.php --> /actualites.php?cat=1&alias=article
http://yourdomain.com/e/1-article.php --> /equipe.php?id_equipe=1&alias=article
Without that /a/ or /e/, there's no way to tell what to map to. If you don't use something like that, you'll need to do all validation in your php.

Resources