Url rewrite using htaccess change query string in base url - .htaccess

I'm trying to remove string from the end of URL:
For example i have a structure like this:
http://sitename.com/category/first-category-name.php/?post_type=question
http://sitename.com/category/second-category-name.php/?post_type=question
http://sitename.com/category/...-category-name.php/?post_type=question
I would like to convert url from http://sitename.com/category/-----category-name/?post_type=question to http://sitename.com/category/-----category-name/post_type/question from the end of URL.

You can conditionally redirect if the post_type value exists in the query string.
// Get the category. This is here for example purposes.
$categoryName = 'first-category-name';
if (!empty($_GET['post_type'])) {
$postType = $_GET['post_type'];
header("Location: http://sitename.com/category/$categoryName/post_type/$postType", true, 301);
}
For security, you probably want to make sure $category and $postType are sanitized.

Related

How to check if two URL's lead to the same path?

I'm building a URL Shortener, and I've decided to recyle the short ID's if possible to save space in my database. How can i check if 2 URL's lead to the same path?
For example, let's say a user generates a short URL for https://google.com/.
My app generates the following short id: jkU3
So if this user visits https://tiny.url/jkU3 my express server will redirect the visitor to https://google.com/.
This works like a charm, but know let's imagine another person visits https://tiny.url/ and generates a short URL for https://google.com. And another one comes and generates a short URL for https://www.google.com/, and another one comes and generates one for https://www.google.com. You get the point..
So far my app would have wasted 4 short ID's.
How can i prevent this from happening? Is there a regex for this?
This is the current code I have for generating short URL's:
app.post("/", (req: Request, res: Response) => {
const shortUrl: string = nanoid(4);
const destination: string = req.body.destination;
UrlSchema.create({
_id: mongoose.Types.ObjectId(),
origin: shortUrl,
destination: destination,
}).then(() => {
// Unique Id
res.json(shortUrl);
});
});
Before creating a new entry you can check work destination with
const existing = await UrlSchema.findOne({destination:req.body.destination});
if(!existing){
// create new
} else{
// return same
}
This way you will be creating destination if it does not exist already. You can remove tariling slash(/) if it exists to match URLs better,
You've listed four slightly different URLs:
https://www.google.com
https://google.com
https://www.google.com/
https://google.com/
None of these are technically the same https request, though it sounds like you want to assume that the / at the end is optional and thus does not make it a different target URL.
The last two are not guaranteed to be the same host as the first two. For google.com and www.google.com, they are the same host, but this is not guaranteed to be the case for all possible hosts.
If you want to assume that these four are all to the same host no matter what the domain is, then you just have to normalize the URL before you put it in your database and then before assigning a new shortened ID, you search the database for the normalized version of the URL.
In this case, you would remove the www. and remove any trailing slash to create the normalized version of the URL.
function normalizeUrl(url) {
// remove "www." if at first part of hostname
// remove trailing slash
return url.replace(/\/\/www\./, "//").replace(/\/$/, "");
}
Once you've normalized the URL, you search for the normalized URL in your database. If you find it, you use the existing shortener for it. If you don't find it, you add the normalized version to your database with a newly generated shortId.
Here's a demo:
function normalizeUrl(url) {
// remove "www." if at first part of hostname
// remove trailing slash
return url.replace(/\/\/www\./i, "//").replace(/\/$/, "");
}
const testUrls = [
"https://www.google.com",
"https://www.google.com/",
"https://google.com",
"https://google.com/",
];
for (const url of testUrls) {
console.log(normalizeUrl(url));
}
FYI, since hostnames in DNS are not case sensitive, you may also want to force the hostname to lower case to normalize it. Path names or query parameters could be case sensitive (sometimes they are and sometime they are not).
To include the host case sensitivity normalization, you could use this:
function normalizeUrl(url) {
// remove "www." if at first part of hostname
// remove trailing slash
// lowercase host name
return newUrl = url.replace(/\/\/www\./i, "//").replace(/\/$/, "").replace(/\/\/([^/]+)/, function(match, p1) {
// console.log(match, p1);
return "//" + p1.toLowerCase();
});
}
const testUrls = [
"https://www.google.com",
"https://www.google.com/",
"https://google.com",
"https://google.com/",
"https://WWW.google.com",
"https://www.Google.com/",
"https://GOOGLE.com",
"https://google.COM/",
"https://www.Google.com/xxx", // this should be unique
"https://google.COM/XXX", // this should be unique
];
for (const url of testUrls) {
console.log(normalizeUrl(url));
}

Redirect old URL's to new URL pattern

Hi I want to change my current product URL structure to a new one but I want to keep my old ones working because of people who have linked to my products.
How can I do this without manually creating a 301 redirect for each product?
Not sure what Prestashop version you have, just tried in a 1.6.1.6
You can you this override:
<?php
class Dispatcher extends DispatcherCore
{
protected function loadRoutes($id_shop = null)
{
parent::loadRoutes($id_shop);
$language_ids = Language::getIDs();
if (isset($context->language) && !in_array($context->language->id, $language_ids)) {
$language_ids[] = (int)$context->language->id;
}
foreach ($language_ids as $id_lang) {
foreach ($this->default_routes as $id => $route) {
if($id == "product_rule")
$this->addRoute(
'product_rule2',
'{id}-{rewrite}{-:ean13}.xhtml',
'product',
$id_lang,
$route['keywords'],
isset($route['params']) ? $route['params'] : array(),
$id_shop
);
}
}
}
}
In this case I used a second rule for xhtml (without this override it gave a 404). You can change {id}-{rewrite}{-:ean13}.xhtml to the rule you have, then change the rules in SEO to want you want the new one to be.
Please write your ps version. If you use 1.5 or above?
Do you use this structure now {category:/}{id}-{rewrite}{-:ean13}.html ? or
{category:/}{rewrite}{-:ean13}.html or this {category:/}{rewrite}.html
please write more details
depends on it just make htaccess rule
([0-9]+) for id
(.*) for rewrite
and please use RedirectMatch permanent
and set to the result by $1, $2, etc
that guide must help to understand the htaccess url rewriting https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/

URL rewriting using NodeJS

I want to customize my URL rewriting but it seems not working as I'd like it to.
My old code :
var rewrite = require('express-urlrewrite');
exports.rewrite = function(app){
app.use(rewrite('/p/:id/:seoUrl', '/page/show/$1/$2'));
}
In my browser : http://mysite/p/1/seo-title (this URL works)
My new code :
var rewrite = require('express-urlrewrite');
exports.rewrite = function(app){
app.use(rewrite('/:seoUrl', '/page/show/$1/$2'));
}
In my browser : http://mysite/seo-title (ID not found)
Using NodeJS, is there a way to exclude the ID in the URL?
well. if you take a close look at this: '/page/show/$1/$2' you might notice that it accepts two arguments.
since you removed :id you'd have to replace $1 with a static id or remove it completely aswell as you have to change $2 to $1
so in the end your code might look like this: app.use(rewrite('/:seoUrl', '/page/show/1/$1'));
or like this: app.use(rewrite('/:seoUrl', '/page/show/$1'));

Using htaccess to redirect .nl to .com/nl

I want to send users who use a country code in their adressbar to be redirected to the right subpage by using the htaccess file.
for example:
www.example.nl
redirect to:
www.example.com/nl
Any suggestions?
I would suggest you to use the GeoIP service [PHP] to find out the country of your visitor and then do the redirect.
include("geoipcity.inc");
include("geoipregionvars.php");
$gi = geoip_open("/usr/local/share/GeoIP/GeoIPCity.dat",GEOIP_STANDARD);
$getcountry = geoip_record_by_addr($gi,$_SERVER['REMOTE_ADDR']);
if ( $getcountry->country_code == "NL" ) {
header('Location: www.example.com/nl');
}
Like this for NL Redirect

CakePHP 2.0: How to redirect a url like /details.php?id=1234 to /articles/show/1234?

I already checked this: CakePHP and .htaccess: how to redirect url with query string but it's not working for me.
I have these kind of url's in Google: /details.php?id=1234 and want this to redirect to the url /details/1234
Is there a way to use cakes redirect: http://book.cakephp.org/2.0/en/development/routing.html#redirect-routing ?
Or do I need to do this in the htaccess? If yes, in which one? The /root/htaccess or the /root/webroot/htaccess?
Please advice!
Thanks so much in advance!
I have a similar situation in my application that I am handling in the following manner:
Basically, I was using a system of URLs that is different than now. Bookmarks are on Facebook and all over the web.... Anyway, people were accessing my page like this
http://www.domain.com/?c=123&a=2261
c=123 refered to the category in which the article belonged to and a=2261 was in reference to the article id that was migrated to my new site. Now my url was like the following:
http://www.domain.com/article/slug-for-the-article-in-question
I used the following code in my app_controller.php
function CheckOldUrl(){
preg_match("/a=(\\d{1,})/ui", $_SERVER['REQUEST_URI'], $matches);
if(!$matches == NULL){
$this->redirect('/articles/articleRedirect/'.$matches[1]);
}
}
Then I setup a function in my articles controller (articleRedirect) to check the right article in DB, get its slug and redirect to the correct new article url.
function articleRedirect($article_id = NULL){
$this->Article->recursive = -1;
$slug = $this->Article->findById($article_id);
if($slug == NULL){
$this->Session->setFlash('This article does not exist!','default',array('class'=>'alert_error'));
$this->redirect('/articles');
}else{
$this->redirect('/article/'.$slug['Article']['slug']);
}
}
Anyway, for you I would suggest the following, although I have not tested it....
function beforeFilter(){
...
$this->CheckOldUrl();
...
}
function CheckOldUrl(){
preg_match("/id=(\\d{1,})/ui", $_SERVER['REQUEST_URI'], $matches);
if(!$matches == NULL){
$this->redirect('/articles/show/'.$matches[1]);
}
}

Resources