Htaccess, Apache, and Rewrites! Oh, My!

Total Page:16

File Type:pdf, Size:1020Kb

Htaccess, Apache, and Rewrites! Oh, My! Crucial Web Hosting » Blog » Htaccess, Apache, A... http://www.crucialwebhost.com/blog/htaccess-apa... Home Blog Htaccess, Apache, And Rewrites! Oh, My! Htaccess, Apache, And Rewrites! Oh, My! As a web designer or developer, it is important to know how to use the htaccess file to your advantage. It is a very powerful tool, and can even work as a deterrent for bandwidth thieves, exploits, and hackers. Below are some common examples of rules to consider when developing websites. We hope you find them useful. Jump To Redirect Example 1. Rewrite Engine 2. Basic Redirect 3. HTML to PHP 4. Remove File Extensions 5. Add WWW To Domain 6. Remove WWW From Domain 7. Add Trailing Slash 8. Remove Trailing Slash 9. Remove Query String 10. Remove Trailing Question Mark 11. Remove Trailing Index File 12. Remove Index File From URL 13. HTTP to HTTPS 14. HTTPS to HTTP 15. Deny Access To Htaccess 16. Enable Caching 17. Disable Caching On Dynamic Pages 18. Example Htaccess File Rewrite Engine In order for any of these rules to work, the first thing we need to do is turn on the rewrite engine. 1. Options +FollowSymLinks 2. RewriteEngine On 1 of 17 04/11/2008 02:00 PM Crucial Web Hosting » Blog » Htaccess, Apache, A... http://www.crucialwebhost.com/blog/htaccess-apa... The first line of code is a security feature that must be enabled for the rewrite rules to work. In most cases, this is already set up by your host, but it won’t hurt to list it again here. This is just telling the server to follow symbolic links. If you are a Windows user, this would be the same as a shortcut. You may not need the first line though, but it is important to understand why you might need to add it. The second line is what actually turns the rewrite engine on. It does nothing for us though. Basic Redirect There are a couple reasons why you would use a basic redirect. Let’s say you just re-structured and organized your files, but you wanted visitors who were still using the old filename to be able to access the new one. They might have bookmarked the page, or found it in a search engine. 1. RewriteRule ^old-filename.php$ /new-filename.php [R=301,L] The first part of the rule is looking for a request for old-filename.php. If it finds it, it will visually redirect the visitor to new-filename.php. In the last part of the rule, we’re using a redirect flag with a 301 code attribute attached, which is a permanent redirect. If we had just used [R] without adding the code parameter, the code would have been a 302, which is a temporary redirect. We want to use a permanent one so search engines know that the old file does not exist anymore. There is also a caret in front of old-filename.php and a dollar sign at the end. These are regular expressions, and the caret tells us to the request must start with this, while the dollar sign means it must end with this. We will talk more about flags and regular expressions in an upcoming article. The last thing we want to point out is the forward slash in front of new-filename.php. If we were to specify the base path for rewriting, we would not need this, but since we did not, we need to add it. If we wanted to drop it though, we would add the following directive after we turn the rewrite engine on: 1. RewriteBase / It just depends on what you find easier. The base for rewriting URLs will always be the root of your website. There is also another way to perform redirects without using mod_rewrite. We can use mod_alias instead: 2 of 17 04/11/2008 02:00 PM Crucial Web Hosting » Blog » Htaccess, Apache, A... http://www.crucialwebhost.com/blog/htaccess-apa... 1. Redirect 301 /old-filename.php http://www.domain.com/new-filename.php 2. Redirect Permanent /old-filename.php http://www.domain.com/new-filename.php Both lines of code work, but you only need to use one. We could also do a temporary redirect: 1. Redirect /old-filename.php http://www.domain.com/new-filename.php 2. Redirect 302 /old-filename.php http://www.domain.com/new-filename.php 3. Redirect Temp /old-filename.php http://www.domain.com/new-filename.php All three lines would work, but we only need to use one. If you don’t specify anything after the Redirect, it will use the default temporary redirect (a 302), just like our redirect flag. HTML to PHP What if we recently converted our site to PHP, but all of the old filenames were using the .html extension? It wouldn’t make sense to create a redirect rule for each file. So instead we could do this: 1. RewriteRule ^(.*).html /$1.php [R=301,L] Anytime a request for a file with the .html extension is made, it will be redirected to the same file but with our new .php extension. Of course, we could always change the way Apache handled HTML files, letting them act like PHP files instead. 1. AddType application/x-httpd-php .php .html .htm Remove File Extensions But file extensions are so ugly! Maybe you want to give the illusion that your individual files are actually directories: 1. RewriteRule ^(.*)/$ /$1.php [L] So we could have a bunch of files in our root directory that looked like this: 1. http://www.domain.com/services.php 2. http://www.domain.com/products.php 3. http://www.domain.com/about.php 3 of 17 04/11/2008 02:00 PM Crucial Web Hosting » Blog » Htaccess, Apache, A... http://www.crucialwebhost.com/blog/htaccess-apa... 4. http://www.domain.com/links.php 5. http://www.domain.com/contact.php And they could instead look like this: 1. http://www.domain.com/services/ 2. http://www.domain.com/products/ 3. http://www.domain.com/about/ 4. http://www.domain.com/links/ 5. http://www.domain.com/contact/ Add WWW To Domain One of the first things you should decide when you create a new site, or at least early on, is if you’re going to have the WWW in your domain or not. This is important not only aesthetically, but for search engine optimization. By forcing visitors and search engines to your preferred domain, you can guarantee that you won’t end up with duplicate results or different page ranks for your domain with or without the WWW. I personally think domains look naked without them, and there is a reason why we use the WWW in the first place. See, not everyone enters the WWW when they type in a domain. Some leave it out, while others always type it in. If you’re familiar with the keyboard shortcuts built in to your browser, simply typing the domain without the TLD extension (e.g. domain instead of domain.com) and then holding CTRL + Enter will add the www. before the domain name, and a .com after it (other keyboard shortcuts will use .org or .net). You might have been to a site before and noticed that if you don’t type the WWW in, you get an error page telling you that the page cannot be found. It all depends on how your host or server administrator has decided to set this up, but usually your domain will work with or without the WWW. 1. RewriteCond %{HTTP_HOST} ^domain.com$ [NC] 2. RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L] The first line is a rewrite condition that is looking at the current hostname, which can be something like www.domain.com, domain.com, sub.domain.com, or an IP address. The second part of this line is checking to see if the hostname does not have a WWW in front of it, and if it does not find one, it moves to the second line, and redirects all requests 4 of 17 04/11/2008 02:00 PM Crucial Web Hosting » Blog » Htaccess, Apache, A... http://www.crucialwebhost.com/blog/htaccess-apa... to the same domain with the WWW in front of it. If the WWW is already there, then this rule is ignored because it would not meet the condition in the first line. The NC flag at the end of the first line just means to ignore the case of what the request is, so we could type in DoMain.com and it wouldn’t matter. The R=301 flag means we are going to visually redirect the visitor to our domain with the WWW. A 301 code is a permanent redirect, and that is important because it also tells search engines that this isn’t a temporary thing (which is what a 302 code would be). The L flag means this is the last rule to follow in this set. Any other rules or conditions after this will not be factored into this rule. Remove WWW From Domain Others prefer to remove the WWW, and for this rule, we’re just doing the exact opposite of the previous example. 1. RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC] 2. RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L] Add Trailing Slash The use of a trailing slash is also important to consider. By default, your web browser will add a trailing slash to the end of a URL. It makes sense to have the trailing slash too—except for files—because it means we’re in a directory.
Recommended publications
  • Nginx Essentials.Pdf
    www.it-ebooks.info Nginx Essentials Excel in Nginx quickly by learning to use its most essential features in real-life applications Valery Kholodkov BIRMINGHAM - MUMBAI www.it-ebooks.info Nginx Essentials Copyright © 2015 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: July 2015 Production reference: 1170715 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78528-953-8 www.packtpub.com www.it-ebooks.info Credits Author Project Coordinator Valery Kholodkov Vijay Kushlani Reviewers Proofreader Markus Jelsma Safis Editing Jesse Estill Lawson Daniel Parraz Indexer Priya Sane Commissioning Editor Dipika Gaonkar Production Coordinator Shantanu N. Zagade Acquisition Editor Usha Iyer Cover Work Shantanu N. Zagade Content Development Editor Nikhil Potdukhe Technical Editor Manali Gonsalves Copy Editor Roshni Banerjee www.it-ebooks.info About the Author Valery Kholodkov is a seasoned IT professional with a decade of experience in creating, building, scaling, and maintaining industrial-grade web services, web applications, and mobile application backends.
    [Show full text]
  • A Flexible Framework for File System Benchmarking &Pivot
    ;login SPRING 2016 VOL. 41, NO. 1 : & Filebench: A Flexible Framework for File System Benchmarking Vasily Tarasov, Erez Zadok, and Spencer Shepler & Pivot Tracing: Dynamic Causal Monitoring for Distributed Systems Jonathan Mace, Ryan Roelke, and Rodrigo Fonseca & Streaming Systems and Architectures: Kafka, Spark, Storm, and Flink Jayant Shekhar and Amandeep Khurana & BeyondCorp: Design to Deployment at Google Barclay Osborn, Justin McWilliams, Betsy Beyer, and Max Saltonstall Columns Red/Blue Functions: How Python 3.5’s Async IO Creates a Division Among Function David Beazley Using RPCs in Go Kelsey Hightower Defining Interfaces with Swagger David N. Blank-Edelman Getting Beyond the Hero Sysadmin and Monitoring Silos Dave Josephsen Betting on Growth vs Magnitude Dan Geer Supporting RFCs and Pondering New Protocols Robert G. Ferrell UPCOMING EVENTS NSDI ’16: 13th USENIX Symposium on Networked USENIX Security ’16: 25th USENIX Security Systems Design and Implementation Symposium March 16–18, 2016, Santa Clara, CA, USA August 10–12, 2016, Austin, TX, USA www.usenix.org/nsdi16 www.usenix.org/sec16 Co-located with NSDI ’16 Co-located with USENIX Security ’16 CoolDC ’16: USENIX Workshop on Cool Topics on WOOT ’16: 10th USENIX Workshop on Offensive Sustainable Data Centers Technologies March 19, 2016 August 8–9, 2016 www.usenix.org/cooldc16 Submissions due May 17, 2016 www.usenix.org/woot16 SREcon16 CSET ’16: 9th Workshop on Cyber Security April 7–8, 2016, Santa Clara, CA, USA Experimentation and Test www.usenix.org/srecon16 August 8, 2016 Submissions
    [Show full text]
  • Admin Tools for Joomla 4 Nicholas K
    Admin Tools for Joomla 4 Nicholas K. Dionysopoulos Admin Tools for Joomla 4 Nicholas K. Dionysopoulos Copyright © 2010-2021 Akeeba Ltd Abstract This book covers the use of the Admin Tools site security component, module and plugin bundle for sites powered by Joomla!™ 4. Both the free Admin Tools Core and the subscription-based Admin Tools Professional editions are completely covered. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the appendix entitled "The GNU Free Documentation License". Table of Contents 1. Getting Started .......................................................................................................................... 1 1. What is Admin Tools? ....................................................................................................... 1 1.1. Disclaimer ............................................................................................................. 1 1.2. The philosophy ....................................................................................................... 2 2. Server environment requirements ......................................................................................... 2 3. Installing Admin Tools ......................................................................................................
    [Show full text]
  • Pragmaticperl-Interviews-A4.Pdf
    Pragmatic Perl Interviews pragmaticperl.com 2013—2015 Editor and interviewer: Viacheslav Tykhanovskyi Covers: Marko Ivanyk Revision: 2018-03-02 11:22 © Pragmatic Perl Contents 1 Preface .......................................... 1 2 Alexis Sukrieh (April 2013) ............................... 2 3 Sawyer X (May 2013) .................................. 10 4 Stevan Little (September 2013) ............................. 17 5 chromatic (October 2013) ................................ 22 6 Marc Lehmann (November 2013) ............................ 29 7 Tokuhiro Matsuno (January 2014) ........................... 46 8 Randal Schwartz (February 2014) ........................... 53 9 Christian Walde (May 2014) .............................. 56 10 Florian Ragwitz (rafl) (June 2014) ........................... 62 11 Curtis “Ovid” Poe (September 2014) .......................... 70 12 Leon Timmermans (October 2014) ........................... 77 13 Olaf Alders (December 2014) .............................. 81 14 Ricardo Signes (January 2015) ............................. 87 15 Neil Bowers (February 2015) .............................. 94 16 Renée Bäcker (June 2015) ................................ 102 17 David Golden (July 2015) ................................ 109 18 Philippe Bruhat (Book) (August 2015) . 115 19 Author .......................................... 123 i Preface 1 Preface Hello there! You have downloaded a compilation of interviews done with Perl pro- grammers in Pragmatic Perl journal from 2013 to 2015. Since the journal itself is in Russian
    [Show full text]
  • Modern Perl, Fourth Edition
    Prepared exclusively for none ofyourbusiness Prepared exclusively for none ofyourbusiness Early Praise for Modern Perl, Fourth Edition A dozen years ago I was sure I knew what Perl looked like: unreadable and obscure. chromatic showed me beautiful, structured expressive code then. He’s the right guy to teach Modern Perl. He was writing it before it existed. ➤ Daniel Steinberg President, DimSumThinking, Inc. A tour de force of idiomatic code, Modern Perl teaches you not just “how” but also “why.” ➤ David Farrell Editor, PerlTricks.com If I had to pick a single book to teach Perl 5, this is the one I’d choose. As I read it, I was reminded of the first time I read K&R. It will teach everything that one needs to know to write Perl 5 well. ➤ David Golden Member, Perl 5 Porters, Autopragmatic, LLC I’m about to teach a new hire Perl using the first edition of Modern Perl. I’d much rather use the updated copy! ➤ Belden Lyman Principal Software Engineer, MediaMath It’s not the Perl book you deserve. It’s the Perl book you need. ➤ Gizmo Mathboy Co-founder, Greater Lafayette Open Source Symposium (GLOSSY) Prepared exclusively for none ofyourbusiness We've left this page blank to make the page numbers the same in the electronic and paper books. We tried just leaving it out, but then people wrote us to ask about the missing pages. Anyway, Eddy the Gerbil wanted to say “hello.” Prepared exclusively for none ofyourbusiness Modern Perl, Fourth Edition chromatic The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina Prepared exclusively for none ofyourbusiness Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks.
    [Show full text]
  • Apache Redirect Post Request
    Apache Redirect Post Request neverGreekish buttonholing and terminable so uncompromisingly Sayre never mess-ups or shakes his anybaldmoney! prompt stunningly. Stan waxen stably? Lengthy Claudio If you want with care because module to leave the redirect post request This implementation detail is not important to know for the majority of the simple rewrites that you will ever write or use. It is common practice to redirect one URL to another. If everything is a go, load balancer, as they completely break the user experience. We have a way, from posting data it makes transition as with get request, you research paper? IT professional working in the North West of the UK. Instead of returning a result page immediately in response to POST request, or URL redirection, you might require to generate a certificate and key for HTTPs. Server variables change dynamically, the firewall rules apply to all of your backend instances in the VPC network. Have you enabled HTTPs on your web server? Seat Economy Plus Review! You can use validate in the input form for its original purpose: to verify input data. Software Engineering Stack Exchange is a question and answer site for professionals, it loads the same object from Current Items again. The comma separated list of encryption ciphers that this socket is allowed to use. And will images be redirected properly? If nothing is returned the syntax is correct and Nginx has to be reloaded for the redirects to take effect. In other words, so it continues. Can you please explain how redirect reflects Google search result? Even doing further tests based on variables set earlier.
    [Show full text]
  • Presentation By: Lilian Thairu AGENDA
    APACHE Presentation by: Lilian Thairu AGENDA Introduction Where to get Apache Versions Licensing Use Features Server & Supporting programs Competitors Market structure Pros & Cons Apache Vs Other servers Presentation by: Lilian Thairu Apache Web Server Introduction Often referred to as simply Apache is a public-domain open source Web server developed by a group of programmers of about 20 volunteers called the Apache Software Group. Apache was born in early 1995, as free Web server software based around NCSA httpd 1.3, which was the most popular Web server as at that time, and with a bunch of software patches. From that it earned it's name, which stands for "A PAtCHY server." Since then, it has been completely re- written, and has become the most popular WWW server on the Internet. Presentation by: Lilian Thairu ........Introduction Apache lends itself particularly well to projects that are heavily Java based. It offers superior handling of the Java Database Connectivity (JDBC) application program interface. The original version was written for UNIX,but there are now versions run under other platforms. Majority of all web servers using Apache are Linux web servers.Presentation by: Lilian Thairu .......Introduction The Apache web server is a program that parses types of hypertext markup language(HTML) and sends it back to you as a human readable web page. It was the first alternative to the Netscape Communications Corporations web server and it has since evolved to rival other Unix Based web servers in terms of functioning and performance. It has played a key role in the initial growth of the WWW and has been the most popular HTTP server on the WWW.
    [Show full text]
  • An Illumination of the Template Enigma : Software Code Generation with Templates
    An illumination of the template enigma : software code generation with templates Citation for published version (APA): Arnoldus, B. J. (2011). An illumination of the template enigma : software code generation with templates. Technische Universiteit Eindhoven. https://doi.org/10.6100/IR693494 DOI: 10.6100/IR693494 Document status and date: Published: 01/01/2011 Document Version: Publisher’s PDF, also known as Version of Record (includes final page, issue and volume numbers) Please check the document version of this publication: • A submitted manuscript is the version of the article upon submission and before peer-review. There can be important differences between the submitted version and the official published version of record. People interested in the research are advised to contact the author for the final version of the publication, or visit the DOI to the publisher's website. • The final author version and the galley proof are versions of the publication after peer review. • The final published version features the final layout of the paper including the volume, issue and page numbers. Link to publication General rights Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights. • Users may download and print one copy of any publication from the public portal for the purpose of private study or research. • You may not further distribute the material or use it for any profit-making activity or commercial gain • You may freely distribute the URL identifying the publication in the public portal.
    [Show full text]
  • The Webp Manual Was Written by Jeremy Wagner
    IMPRINT Imprint © 2018 Smashing Media AG, Freiburg, Germany ISBN (PDF): 978-3-945749-67-8 Cover Design: Ricardo Gimenes eBook Production: Cosima Mielke Tools: Elja Friedman Syntax Highlighting: Prism by Lea Verou Idea & Concept: Smashing Media AG The WebP Manual was written by Jeremy Wagner. 2 Table of Contents Foreword ........................................................................................4 WebP Basics..................................................................................6 Performance................................................................................ 21 Converting Images To WebP ................................................34 Using WebP Images.................................................................62 In Closing.....................................................................................78 Appendix...................................................................................... 80 Thanks...........................................................................................83 About The Author ..................................................................... 84 3 FOREWORD Foreword Performance matters now more than ever. What we send over the wire, how we send it, and how much of it we send matters. Because users matter. Web perfor- mance is a vast subject with many nooks and crannies, and all deserve their due attention. Of serious concern, however, is the role of media in performance, specifically images. Images are powerful. Engaging visuals evoke visceral feelings.
    [Show full text]
  • Openqa Documentation
    openQA Documentation openQA Team Table of Contents openQA starter guide. 1 Introduction . 2 Architecture. 3 Basic concepts . 4 Glossary . 4 Jobs . 5 Needles . 6 Areas. 6 Access management . 7 Job groups . 7 Cleanup . 8 Using the client script . 9 Testing openSUSE or Fedora . 10 Getting tests. 10 Getting openQA configuration . 10 Adding a new ISO to test . 11 Pitfalls . 12 openQA installation guide . 13 Introduction . 14 Quick bootstrapping under openSUSE . 15 Directly on your machine . 15 openQA in a container . 15 Container based setup . 16 Custom installation - repositories and procedure . 17 Official repositories. 17 Development version repository . 17 Installation . 18 System requirements . 19 Basic configuration . 20 Apache proxy . 20 TLS/SSL. 20 Database . 21 Example for connecting to local PostgreSQL database . 21 Example for connecting to remote PostgreSQL database . 21 User authentication. 21 OpenID. 22 OAuth2. 22 Fake . 22 Run the web UI . 24 Run openQA workers . 25 Where to now? . 27 Advanced configuration. 28 Cleanup . 28 Setting up git support . 28 Referer settings to auto-mark important jobs . 29 Worker settings . 29 Further systemd units for the worker . 29 Stopping/restarting workers without interrupting currently running jobs . 30 Configuring remote workers . 31 Configuring AMQP message emission . 31 Configuring worker to use more than one openQA server . 31 Asset and test/needle caching. ..
    [Show full text]
  • Magento Performance Testing Guidelines Ii
    TABLE OF CONTENTS OVERVIEW .................................................................................................................................................................. 2 Methodology ....................................................................................................................................................... 2 Objectives ............................................................................................................................................................ 2 Terminology ........................................................................................................................................................ 2 Recommended Test Protocol ........................................................................................................................... 3 CLOUD SERVICES VS. DEDICATED HOSTING ......................................................................................................... 4 SYSTEM RESOURCE MONITORING ......................................................................................................................... 4 MAGENTO CONFIGURATION SETTINGS ............................................................................................................... 5 Use Flat Catalog .................................................................................................................................................. 5 Merge JavaScript & CSS .....................................................................................................................................
    [Show full text]
  • Nginx HTTP Server
    Nginx HTTP Server Adopt Nginx for your web applications to make the most of your infrastructure and serve pages faster than ever Clément Nedelcu BIRMINGHAM - MUMBAI Nginx HTTP Server Copyright © 2010 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: July 2010 Production Reference: 1140710 Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-849510-86-8 www.packtpub.com Cover Image by Vinayak Chittar ([email protected]) Credits Author Editorial Team Leader Clément Nedelcu Aanchal Kumar Reviewers Project Team Leader Pascal Charest Lata Basantani Manlio Perillo Project Coordinator Acquisition Editor Jovita Pinto Usha Iyer Proofreader Development Editor Lynda Sliwoski Wilson D'souza Graphics Technical Editor Geetanjali Sawant Kartikey Pandey Production Coordinator Copy Editor Aparna Bhagat Leonard D'Silva Cover Work Indexers Aparna Bhagat Hemangini Bari Tejal Daruwale About the Author Clément Nedelcu was born and raised in France, and studied in U.K., French, and Chinese universities.
    [Show full text]