Rewriting Apache url not working properly

I am trying to use the apache-rewrite rule to translate the following URL:

http://localhost/foo/bar/news.php?id=24

In this format:

http://localhost/foo/bar/news/foo-bar

The number 24 is the id random row from the MySQL table, which also contains the title and content fields.

 MariaDB [blog]> select * from articles; +----+---------+----------+ | id | title | content | +----+---------+----------+ | 1 | foo-bar | bla bla | +----+---------+----------+ 1 row in set (0.00 sec) 

I have the following rule inside .htaccess :

 RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l ^news/([A_Za_z0_9_]+)$ DIRECTORY/AID/news.php?id=$1 [QSA,L] 

I also have PHP code that generates a link like this:

 $link = "<a href='news.php?id={$row['id']}'></a>"; echo $link; 

However, I cannot force the rewrite rule to change the path as the desired end result.

+7
source share
12 answers

First of all, you will need to change the href in html to specify a new URL format

 function news_preview() { $query = "SELECT * FROM news ORDER BY id DESC LIMIT 5 "; $result = mysql_query($query) or die(mysql_error()); while($row=mysql_fetch_array($result)) { echo "<a href=\"/news/$row[id]\"> ". substr($row['title'], 0,26)."...</a><br/>".; } } 

As a result, URLs such as http://localhost/news/24 generated

Please note that I removed /DIRECTORY/AID from the URL, since htaccess offers you to specify the URL, unlike what you specified in the text.

But now go to the url type http://localhost/news/this_is_article_title . Since there is no correlation between this_is_article_title and id 24 , the only way to achieve this is to either add an identifier to the URL or get a PHP version of the news article with this header in the database.

This last solution, however, has some problems as you cannot just name the title in the url. You need to avoid characters. You also need to add an index for the title bar in the database for better performance.

So, I will go with the first solution. We will generate URLs like this

http://localhost/news/24/this_is_article_title

Php part first

 function news_preview() { $query = "SELECT * FROM news ORDER BY id DESC LIMIT 5 "; $result = mysql_query($query) or die(mysql_error()); while($row=mysql_fetch_array($result)) { $url = "/news/$row[id]/".preg_replace('/[^a-zA-Z0-9-_]/', '_', $row['title']); echo "<a href=\"$url\"> ". substr($row['title'], 0,26)."...</a><br/>".; } } 

Next comes the htaccess part.

 RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteRule ^news/([0-9]+)/([A-Za-z0-9_-]+)$ DIRECTORY/AID/news.php?id=$1 [QSA,L] 

That should do it, I think.

+2
source

The wildcard (Real) URL has a -Code- number to identify the link (as per your description): http: //localhost/DIRECTORY/AID/news.php? news = 42

This code is 42 in this case, but the URL you want to display does not have it. Without this number, we always get 404 error. Is it like input only: http: //localhost/DIRECTORY/AID/news.php? News =

You must change the URL that you want to display, for example, adding the code after the "/". There may be a hyphen, etc., but the regular expression must be changed accordingly.

Here is an example input: http: // localhost / news / 42 / to go to http: //localhost/DIRECTORY/AID/news.php? news = 42

 RewriteEngine On RewriteRule ^news/([0-9]+)/?$ DIRECTORY/AID/news.php?news=$1 [NC,L] 

That is all you need. To test this example, insert this code only in news.php at http: // localhost / DIRECTORY / AID /

 <?php if ( $_GET[ 'news' ] == '42' ) { echo "HERE I AM<br /><br />"; } ?> 

UPDATED as described by OP. Any name can be used instead of This_is_news :

 RewriteEngine On RewriteRule ^news/([0-9a-zA-Z-_]+)/?$ DIRECTORY/AID/news.php?news=$1 [NC,L] 
+4
source

Post a RewriteBase right after RewriteEngine On It will correctly configure the rewrite mechanism before you start the redirection

+1
source

Unfortunately, I cannot answer your question in PHP or Apache (although I use a converted REST converter manually to create URLs in my current project), but from what I understand, you want your user to print http : //localhost/DIRECTORY/AID/article.php? a_id = 24 , and the address bar should end as http: // localhost / DIRECTORY / AID / news / this_is_article_title .

I do not quite understand what advantages this gives you, and please remember that my solution will NOT allow the end user to enter a RESTful URL and end on a page with a QueryString address. To do this, you will need additional work, and even more work to synchronize with the database (I would recommend a script that releases the RESTFUL URL, requests a database for the topic, then returns an identifier or page content ... but another question about the stack overflowing for another day .

SOLUTION My proposed solution requires HTML5 doctype and very lightly sprinkled Javascript.

 history.replaceState(null, "history title here", "news/this_is_article_title"); 

This means that it changes the URL in the address bar without causing page redirection, reloading, or anything else. This javascript can be dynamically written with your PHP, since the page is being served, the address is being updated. The higher the document, the faster this change.

Here's the jsFiddle link: http://jsfiddle.net/uT3RP/1/

Unfortunately, they run the code in an iframe, so it does not control the main address bar, so I included a warning that it will tell the location of the address bar, for proof. These are not the most elegant solutions. I would not even recommend doing what you are doing without failing to make sure that the display URL can be used to go to the same page. Disclaimer ... your problem is solved with 1 line js and change doctype (if you don't use HTML5)

You can stop flogging bad htaccess and continue your project :)

+1
source

This is a problem with the URL-Rewrite and String-to-Id algorithm.

First of all, remember that ever your URL is changed using a rewriting module, the url in the browser panel always contains a post parameter, such as id or string (about your news).

Now to the question. Our goal is to simply rewrite Url:

 http://localhost/DIRECTORY/AID/news/this_is_article_title 

in

 http://localhost/DIRECTORY/AID/news.php?a_id=24 

With the rewrite module, we can only rewrite it to:

 http://localhost/DIRECTORY/AID/news.php?title=this_is_article_title 

and here is the htaccess part tested by alrealdy on htaccess-online-tester

 RewriteRule ^DIRECTORY/AID/news/([A-Za-z0-9_]+)$ DIRECTORY/AID/news.php?title=$1 [QSA,L] 

The rest of the work is an algorithm for comparing the headline with news that the rewrite module cannot help us (especially you manually rewrite the URL one by one). We can use the php code below:

 <?php //write url reflect to news title. function build_news_url_by_title(){ $query = "SELECT * FROM news ORDER BY id DESC LIMIT 5"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ echo "<a href=\"news/".strtr(substr($row['title'], 0,26), " ", "_")."\">".substr($row['title'], 0,26)."</a>"; } } function get_news_by_title($title){ $real_title = strtr($title, "_", " "); $query = "SELECT * FROM news WHERE title LIKE %".$real_title."% LIMIT 1"; return mysql_query($query) or die(mysql_error()); } $title = $_POST['title']; $news = get_news_by_title($title); //some code return the news ... 

So url:

 http://localhost/DIRECTORY/AID/news/this_is_article_title 

may also tell us the news.

Finally, from the steps above, if we type url

 http://localhost/DIRECTORY/AID/news/this_is_article_title 

in the browser bar, it can also give us news. And he has nothing to do with stupid ID. And although there may be some errors with the code above, do not put it on your product server.

+1
source

Do you see if this works?

 RewriteEngine On RewriteBase /DIRECTORY/AID/ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l ^news/([A-Za-z0-9_]+)$ news.php?id=$1 [QSA,L] 

EDIT: Fixed definitions of regex character classes.

+1
source

You are missing the URL header. If you want to show this in the url, you must also include it in the link, for example:

 <a href="news.php?news_id=$id&title=$url_tile"> 
+1
source

This seems to be a difficult problem, because you do not know where it really does wrong.

I would suggest you divide what you want to do into small parts, and make each of them work correctly before combining them. For example:

  1. Make sure .htaccess file is readable and can do some simple thing, preventing directory indexing for instance. 2. Make sure you can redirect something with simple html code. 3. Make sure you can run Felipe example code successfully. From here you can get good picture of what is going on. 

And as a note:

Most often rewrite:

 http://localhost/DIRECTORY/AID/news.php?a_id=24 TO --> http://localhost/DIRECTORY/AID/news/24_this_is_article_title 

Please note that id 24 is still being ported to the rewritten URL. This will simplify template matching and avoid unnecessary duplicate header processing.

+1
source

Change the link:

 echo "<a href=\"news.php?news=$row[id]\"> ". substr($row['title'], 0,26)."</a> 

to

 echo "<a href=\"news/$row['title']\">".$row['title']."</a>" 

So the link would be news/$row['title'] instead of news.php?id=... And now on the page DIRECOTORY/AID/news.php you should get an id and check if it is an OR number, and in text format match $row['title'] , and then load the pages accordingly.

Notes:

  • $ Row ['title'] is assumed to be unique on all other lines.
  • The header does not contain non-HTML content, in which case you will have to have the Escape URL with these characters.

If the title is not unique, you should probably make news/{id}/{title} and then rewrite it to DIRECTORY/AID/news.php?id={id}&title={title} , and then you can defer it from the identifier instead of the header.

Hope this helps.

+1
source

If you think your .htaccess file .htaccess not working properly, this is a server configuration issue and will most likely work with the AllowOverride directive in the Apache configuration.

In your http.conf file, find the section that looks like this:

 <Directory> Options FollowSymLinks AllowOverride None </Directory> 

Modify the AllowOverride directive to enable All .

 <Directory> Options FollowSymLinks AllowOverride All </Directory> 

The next thing to do is to enable the mod_rewrite module for your XAMPP installation. Find the following line:

 #LoadModule rewrite_module modules/mod_rewrite.so 

Remove # so it looks like this:

 LoadModule rewrite_module modules/mod_rewrite.so 

Restart the Apache service after saving all your changes.

Also make sure that you use the RewriteBase directive in your .htaccess configuration as follows:

 RewriteEngine On RewriteBase /DIRECTORY/AID/ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l ^news/([A-Za-z0-9_]+)(/)?$ news.php?title=$1 [QSA,L] 

The next is to make sure your links point to a Rewrite URL. Your echo line should look something like this:

 echo "<a href=\"news/" . $row['title'] . "\"> " . substr($row['title'], 0, 26) . "...</a><br />"; 

Now, since you can only get headers using this method of rewriting URLs, we need to configure your PHP script to get the content based on the header. If you still want to use "id" only to get the entry, your rewrite URL should contain an "id" in it in one form or another. Typical examples of this form are:

  • news/the_news_title_123
  • news/123_the_news_title
  • news/123/the_news_title
+1
source

I can not comment, so I have to answer.

Reading all the answers and your question, it is not clear what you want. At least for me. You say for example:

http://localhost/DIRECTORY/AID/article.php?a_id=24 to

http://localhost/DIRECTORY/AID/article/this_is_article_title

But I think itโ€™s not entirely right if you donโ€™t want to

http://localhost/DIRECTORY/AID/article.php?a_id=24

to be the URL specified in the address bar of the browser, and if so, what would be the purpose of the redirect? Finally, any visitor will have to enter exactly what you do not want them to print.

I assume you want to enter a friendly URL:

http://localhost/DIRECTORY/AID/article/this_is_article_title , so the question should be the other way around:

http://localhost/DIRECTORY/AID/article/this_is_article_title TO

http://localhost/DIRECTORY/AID/article.php?a_id=24

The next thing that seems obscure is what is displayed in the browser bar? The only answer is the URL you entered. In no case can it show anything else.

In short: if you want http: // localhost / DIRECTORY / AID / article / this_is_article_title to appear in the addres bar, this is what you should enter. The real URL, REPLACEMENT ( http: //localhost/DIRECTORY/AID/article.php? A_id = 24 ), is never displayed and never entered. This is a redirect.

On the other hand, it is unclear how the ID numbers provided by news.php are expected to be converted to strings, such as article / this_is_article_title . ยฟWhere are these lines, how many identification numbers, which algorithm or formula should be used to achieve this conversion, which of these identifiers are โ€œrootโ€, as you mentioned in the comment, and how can they be identified, etc.? You should talk more about this because it seems to be improvised and inconsistent with your previous comments.

Maybe I'm wrong. I am just guessing to try and help with your question.

Please geniuses, do not subvert this answer, read it. I am not trying to answer the question, and I am really far from a genius.

0
source

Looks like you forgot the slash before "news.php".

-2
source

All Articles