{"id":3908,"date":"2026-01-01T16:54:06","date_gmt":"2026-01-01T13:54:06","guid":{"rendered":"https:\/\/www.dchost.com\/blog\/seo-safe-url-structure-changes-with-301-redirects-in-htaccess-and-nginx\/"},"modified":"2026-11-05T00:44:52","modified_gmt":"2026-11-04T21:44:52","slug":"apache-nginx-url-migration-301","status":"publish","type":"post","link":"https:\/\/www.dchost.com\/blog\/en\/apache-nginx-url-migration-301\/","title":{"rendered":"URL Migration with Apache and Nginx 301 Redirects"},"content":{"rendered":"<div class=\"dchost-blog-content-wrapper\"><p>As a website grows, its URL structure may need to change for a new framework, cleaner navigation or reorganised categories. This requires more than rewrite rules: old URLs need appropriate destinations, and internal links and indexing signals need updating. Careful planning reduces the risk of broken links and lost organic traffic, but does not guarantee unchanged rankings.<\/p>\n<p>This article focuses on the practical middle ground: how to change URL structures while reducing SEO risk, using clean 301 redirects on both Apache (.htaccess) and Nginx. We will look at the SEO rules that really matter, the most common redirect patterns (HTTP\u2192HTTPS, non\u2011www\u2192www, trailing slash, moved folders, removed file extensions), and how to translate them into working configuration examples. We will also cover how to test, debug and clean up once your changes go live, so you can identify migration problems and respond promptly.<\/p>\n<div id=\"toc_container\" role=\"navigation\" aria-label=\"Table of Contents\" data-nosnippet class=\"toc_transparent no_bullets toc_numbered toc_title_center\"><p class=\"toc_title\">\u0130\u00e7indekiler<\/p><ul class=\"toc_list\"><li><a href=\"#Why_URL_Structure_Changes_Matter_for_SEO\"><span class=\"toc_number toc_depth_1\">1.<\/span> Why URL Structure Changes Matter for SEO<\/a><\/li><li><a href=\"#Planning_an_SEOSafe_URL_Migration\"><span class=\"toc_number toc_depth_1\">2.<\/span> Planning an SEO\u2011Safe URL Migration<\/a><ul><li><a href=\"#Step_1_Inventory_your_current_URLs\"><span class=\"toc_number toc_depth_2\">2.1.<\/span> Step 1: Inventory your current URLs<\/a><\/li><li><a href=\"#Step_2_Define_the_new_structure_and_mapping_table\"><span class=\"toc_number toc_depth_2\">2.2.<\/span> Step 2: Define the new structure and mapping table<\/a><\/li><li><a href=\"#Step_3_Decide_on_your_canonical_rules\"><span class=\"toc_number toc_depth_2\">2.3.<\/span> Step 3: Decide on your canonical rules<\/a><\/li><li><a href=\"#Step_4_Test_on_staging_if_you_can\"><span class=\"toc_number toc_depth_2\">2.4.<\/span> Step 4: Test on staging if you can<\/a><\/li><\/ul><\/li><li><a href=\"#301_Redirect_Patterns_in_Apache_htaccess\"><span class=\"toc_number toc_depth_1\">3.<\/span> 301 Redirect Patterns in Apache .htaccess<\/a><ul><li><a href=\"#Basic_onetoone_301_redirect\"><span class=\"toc_number toc_depth_2\">3.1.<\/span> Basic one\u2011to\u2011one 301 redirect<\/a><\/li><li><a href=\"#HTTP_to_HTTPS_for_one_named_host\"><span class=\"toc_number toc_depth_2\">3.2.<\/span> HTTP to HTTPS for one named host<\/a><\/li><li><a href=\"#Nonwww_to_www_or_the_reverse\"><span class=\"toc_number toc_depth_2\">3.3.<\/span> Non\u2011www to www (or the reverse)<\/a><\/li><li><a href=\"#Combining_HTTPS_and_host_canonicalisation\"><span class=\"toc_number toc_depth_2\">3.4.<\/span> Combining HTTPS and host canonicalisation<\/a><\/li><li><a href=\"#Removing_or_adding_a_trailing_slash\"><span class=\"toc_number toc_depth_2\">3.5.<\/span> Removing or adding a trailing slash<\/a><\/li><li><a href=\"#Moving_a_whole_folder_category_change\"><span class=\"toc_number toc_depth_2\">3.6.<\/span> Moving a whole folder (category change)<\/a><\/li><li><a href=\"#Removing_php_file_extensions\"><span class=\"toc_number toc_depth_2\">3.7.<\/span> Removing .php file extensions<\/a><\/li><li><a href=\"#Handling_query_strings_safely\"><span class=\"toc_number toc_depth_2\">3.8.<\/span> Handling query strings safely<\/a><\/li><li><a href=\"#When_to_use_410_Gone_instead_of_301\"><span class=\"toc_number toc_depth_2\">3.9.<\/span> When to use 410 (Gone) instead of 301<\/a><\/li><\/ul><\/li><li><a href=\"#301_Redirect_Patterns_in_Nginx\"><span class=\"toc_number toc_depth_1\">4.<\/span> 301 Redirect Patterns in Nginx<\/a><ul><li><a href=\"#Basics_return_vs_rewrite\"><span class=\"toc_number toc_depth_2\">4.1.<\/span> Basics: return vs rewrite<\/a><\/li><li><a href=\"#HTTP_to_HTTPS_redirect_server\"><span class=\"toc_number toc_depth_2\">4.2.<\/span> HTTP to HTTPS redirect server<\/a><\/li><li><a href=\"#Nonwww_to_www_or_reverse_on_Nginx\"><span class=\"toc_number toc_depth_2\">4.3.<\/span> Non\u2011www to www (or reverse) on Nginx<\/a><\/li><li><a href=\"#Folder_move_with_regex\"><span class=\"toc_number toc_depth_2\">4.4.<\/span> Folder move with regex<\/a><\/li><li><a href=\"#Adding_or_removing_trailing_slash\"><span class=\"toc_number toc_depth_2\">4.5.<\/span> Adding or removing trailing slash<\/a><\/li><li><a href=\"#Removing_php_extension_in_Nginx\"><span class=\"toc_number toc_depth_2\">4.6.<\/span> Removing .php extension in Nginx<\/a><\/li><li><a href=\"#Redirecting_individual_pages_clean_syntax\"><span class=\"toc_number toc_depth_2\">4.7.<\/span> Redirecting individual pages (clean syntax)<\/a><\/li><li><a href=\"#Handling_query_strings_in_Nginx_redirects\"><span class=\"toc_number toc_depth_2\">4.8.<\/span> Handling query strings in Nginx redirects<\/a><\/li><\/ul><\/li><li><a href=\"#Testing_Monitoring_and_Cleaning_Up_After_the_Change\"><span class=\"toc_number toc_depth_1\">5.<\/span> Testing, Monitoring and Cleaning Up After the Change<\/a><ul><li><a href=\"#How_to_test_your_redirects\"><span class=\"toc_number toc_depth_2\">5.1.<\/span> How to test your redirects<\/a><\/li><li><a href=\"#Update_internal_links_canonicals_and_sitemaps\"><span class=\"toc_number toc_depth_2\">5.2.<\/span> Update internal links, canonicals and sitemaps<\/a><\/li><li><a href=\"#Watch_logs_and_Search_Console\"><span class=\"toc_number toc_depth_2\">5.3.<\/span> Watch logs and Search Console<\/a><\/li><li><a href=\"#Special_case_changing_domain_names\"><span class=\"toc_number toc_depth_2\">5.4.<\/span> Special case: changing domain names<\/a><\/li><\/ul><\/li><li><a href=\"#Wrapping_Up_Practical_Checklist_and_Next_Steps\"><span class=\"toc_number toc_depth_1\">6.<\/span> Wrapping Up: Practical Checklist and Next Steps<\/a><\/li><\/ul><\/div>\n<h2><span id=\"Why_URL_Structure_Changes_Matter_for_SEO\">Why URL Structure Changes Matter for SEO<\/span><\/h2>\n<p>Folder names alone do not make a URL migration successful; consistency, crawlability and canonical signals matter. When you change URL structures, search engines need to associate the old addresses with the new ones. That can be positive or negative depending on how you handle redirects and internal links.<\/p>\n<p>From an SEO and hosting perspective, three things matter most:<\/p>\n<ul>\n<li><strong>Status codes:<\/strong> 301 and 308 signal permanent moves; 302 and 307 indicate temporary moves. Return 404\/410 for removed content without a relevant replacement. Our <a href=\"https:\/\/www.dchost.com\/blog\/en\/what-http-status-codes-mean-for-seo-and-hosting\/\">HTTP status code guide<\/a> explains the distinction.<\/li>\n<li><strong>Direct destinations:<\/strong> Multiple hops add latency and make redirect paths harder to maintain. Send old URLs directly to the final matching content where possible.<\/li>\n<li><strong>Consistent signals:<\/strong> Choose the canonical host, scheme and page-URL style, then align links, canonical annotations, language alternates and sitemaps.<\/li>\n<\/ul>\n<p>These principles reduce migration risk, but complete URL mapping, testing and post-launch monitoring are still necessary.<\/p>\n<h2><span id=\"Planning_an_SEOSafe_URL_Migration\">Planning an SEO\u2011Safe URL Migration<\/span><\/h2>\n<p>Before we touch .htaccess or Nginx, we need a plan. Missing or incomplete mappings can leave old URLs without appropriate destinations even when the redirect syntax is correct.<\/p>\n<h3><span id=\"Step_1_Inventory_your_current_URLs\">Step 1: Inventory your current URLs<\/span><\/h3>\n<p>Export as many existing URLs as you can:<\/p>\n<ul>\n<li>From your CMS (posts, pages, categories, products)<\/li>\n<li>From your web server logs (high\u2011traffic URLs over the last 6\u201312 months)<\/li>\n<li>From tools like Search Console and crawlers<\/li>\n<\/ul>\n<p>Prioritise URLs that already receive organic traffic or backlinks. Map each to its moved equivalent where one exists; deleted content without an appropriate replacement should return 404 or 410 rather than redirecting to an unrelated page.<\/p>\n<h3><span id=\"Step_2_Define_the_new_structure_and_mapping_table\">Step 2: Define the new structure and mapping table<\/span><\/h3>\n<p>Create a spreadsheet with at least two columns:<\/p>\n<ul>\n<li><strong>Old URL path<\/strong> (e.g. \/blog\/2022\/09\/seo-tips.html)<\/li>\n<li><strong>New URL path<\/strong> (e.g. \/blog\/seo-tips\/)<\/li>\n<\/ul>\n<p>Whenever possible, use predictable patterns instead of one\u2011off rules. For example, if all your blog posts will move from \/blog\/YYYY\/MM\/slug\/ to \/blog\/slug\/, you can cover hundreds of URLs with a single regex redirect, provided slugs remain unique and every destination exists. Handle exceptions with explicit mappings.<\/p>\n<h3><span id=\"Step_3_Decide_on_your_canonical_rules\">Step 3: Decide on your canonical rules<\/span><\/h3>\n<p>Decide once and apply everywhere:<\/p>\n<ul>\n<li>Will you use <strong>www<\/strong> or <strong>bare domain<\/strong> as canonical?<\/li>\n<li>Will page URLs end <strong>with or without trailing slash<\/strong>?<\/li>\n<li>Will you show <strong>file extensions<\/strong> in URLs (.php, .html) or hide them?<\/li>\n<li>Are you enforcing <strong>HTTPS<\/strong> everywhere?<\/li>\n<\/ul>\n<p>Once you decide, your redirect configuration should funnel every variant into a single canonical version (for example, http:\/\/example.com\/blog to https:\/\/www.example.com\/blog\/).<\/p>\n<h3><span id=\"Step_4_Test_on_staging_if_you_can\">Step 4: Test on staging if you can<\/span><\/h3>\n<p>If your hosting setup includes dev or staging environments (for example on a separate <a href=\"https:\/\/www.dchost.com\/vps\">VPS<\/a> or subdomain), deploy your URL changes there first. That is the safest way to catch redirect loops and broken patterns before they affect real users. If you do not yet have a multi\u2011environment workflow, our article on <a href=\"https:\/\/www.dchost.com\/blog\/en\/dev-staging-production-one-vps-or-separate-servers\/\">hosting architecture for dev, staging and production environments<\/a> is a good place to start.<\/p>\n<h2><span id=\"301_Redirect_Patterns_in_Apache_htaccess\">301 Redirect Patterns in Apache .htaccess<\/span><\/h2>\n<p>The following are alternative patterns for Apache 2.4 in the document-root .htaccess file. They require mod_rewrite, suitable AllowOverride permissions and FollowSymLinks or SymLinksIfOwnerMatch enabled by the administrator. Adapt one consistent set; do not paste opposite canonicalisation recipes together. These examples target GET\/HEAD page navigation: a 301 can result in a POST becoming GET, so method-sensitive APIs and forms need a separate migration decision.<\/p>\n<h3><span id=\"Basic_onetoone_301_redirect\">Basic one\u2011to\u2011one 301 redirect<\/span><\/h3>\n<p>For a small number of changed URLs, keep it explicit and readable.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\nRewriteRule ^blog\/2022\/09\/seo-tips\\.html$ https:\/\/www.example.com\/blog\/seo-tips\/ [R=301,L]\nRewriteRule ^shop\/product-123\\.html$ https:\/\/www.example.com\/store\/new-product-slug\/ [R=301,L]\n<\/code><\/pre>\n<p><strong>Notes:<\/strong><\/p>\n<ul>\n<li>These anchored RewriteRule patterns match the complete relative path in the document-root .htaccess context; they do not match a suffix or child path. The target host is fixed. Query strings are retained unless explicitly replaced or discarded.<\/li>\n<li>mod_alias Redirect matches a path prefix and appends additional path information, so Redirect \/old \/new is not an exact-match recipe. RedirectMatch can anchor a regex, but mixing modules still requires understanding their execution phases.<\/li>\n<li>Within the same mod_rewrite ruleset, put specific mappings before broader rules and the application front controller. Textual placement of Redirect lines does not control ordering against mod_rewrite. Keep CMS-generated rule blocks intact.<\/li>\n<\/ul>\n<h3><span id=\"HTTP_to_HTTPS_for_one_named_host\">HTTP to HTTPS for one named host<\/span><\/h3>\n<p>The <a href=\"https:\/\/www.dchost.com\/blog\/en\/full-https-migration-guide-301-redirects-hsts-and-zero-loss-seo\/\">HTTPS migration guide<\/a> covers certificates and rollout. The example below assumes Apache itself terminates the public TLS connection, with the virtual host restricted to example.com. A trusted edge proxy should normally perform public HTTPS redirects itself. If Apache receives HTTP behind TLS termination, its local HTTPS=off state does not mean the visitor used HTTP. Do not trust a client-supplied X-Forwarded-Proto header; any forwarded-scheme design needs an origin reachable only through trusted proxies that overwrite that header.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^example\\.com$ [NC]\nRewriteCond %{HTTPS} off\nRewriteCond %{THE_REQUEST} &quot;\\s(\/[^?\\s]*)(?:\\?|\\s)&quot;\nRewriteRule ^ https:\/\/example.com%1 [R=301,L,NE]\n<\/code><\/pre>\n<p>The host is explicitly allowlisted and the destination host is fixed. THE_REQUEST contains the original, undecoded request line; the final condition captures its path without the query, while the default RewriteRule behavior copies the query. NE avoids double-encoding this already encoded path. This origin-form recipe is not equivalent to appending decoded REQUEST_URI with NE. Test encoded spaces, percent signs, question marks, Unicode and encoded-slash policy on the actual server; do not promise byte preservation for arbitrary other rewrite substitutions. See the <a href=\"https:\/\/httpd.apache.org\/docs\/2.4\/rewrite\/flags.html\" rel=\"nofollow noopener\" target=\"_blank\">Apache rewrite flags reference<\/a> for encoding and processing details.<\/p>\n<h3><span id=\"Nonwww_to_www_or_the_reverse\">Non\u2011www to www (or the reverse)<\/span><\/h3>\n<p>Pick one as canonical. Example: redirect non\u2011www to www.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^example\\.com$ [NC]\nRewriteCond %{THE_REQUEST} &quot;\\s(\/[^?\\s]*)(?:\\?|\\s)&quot;\nRewriteRule ^ https:\/\/www.example.com%1 [R=301,L,NE]\n<\/code><\/pre>\n<p>To go the other way (www \u2192 non\u2011www), invert the condition and target host:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^www\\.example\\.com$ [NC]\nRewriteCond %{THE_REQUEST} &quot;\\s(\/[^?\\s]*)(?:\\?|\\s)&quot;\nRewriteRule ^ https:\/\/example.com%1 [R=301,L,NE]\n<\/code><\/pre>\n<h3><span id=\"Combining_HTTPS_and_host_canonicalisation\">Combining HTTPS and host canonicalisation<\/span><\/h3>\n<p>For direct Apache TLS termination, combine the host and scheme checks while retaining an explicit allowed-host condition. The virtual-host\/default-host configuration must reject unrelated hosts. If a reverse proxy terminates TLS, implement the public scheme policy there or use a separately validated trusted-proxy design; this local HTTPS check must not be copied unchanged.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^(?:www\\.)?example\\.com$ [NC]\nRewriteCond %{HTTPS} off [OR]\nRewriteCond %{HTTP_HOST} !^www\\.example\\.com$ [NC]\nRewriteCond %{THE_REQUEST} &quot;\\s(\/[^?\\s]*)(?:\\?|\\s)&quot;\nRewriteRule ^ https:\/\/www.example.com%1 [R=301,L,NE]\n<\/code><\/pre>\n<p>For the two named hosts on their standard public ports, this sends HTTP bare, HTTP www and HTTPS bare requests to HTTPS www in one hop. HTTPS connections require a valid certificate for the requested name before a redirect can be read. The raw-path capture and NE caveats above apply. Explicit old-to-new content mappings should precede a general canonical rule when both would otherwise redirect the same request.<\/p>\n<h3><span id=\"Removing_or_adding_a_trailing_slash\">Removing or adding a trailing slash<\/span><\/h3>\n<p>Choose one style for application page URLs. The following addition rule excludes existing files and directories and uses a limited 2\u20136-character extension heuristic; it is not a complete filename detector. Apply it only where that policy matches your routes. One-character routes such as \/a are included.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !\\.[a-zA-Z0-9]{2,6}$\nRewriteCond %{THE_REQUEST} &quot;\\s(\/[^?\\s]*)(?:\\?|\\s)&quot;\nRewriteRule ^(.*[^\/])$ https:\/\/www.example.com%1\/ [R=301,L,NE]\n<\/code><\/pre>\n<p>The alternative removal rule also excludes physical directories. Apache mod_dir normally adds a slash to real directories; removing it in another rule can create a loop. Do not disable DirectorySlash as a general workaround.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{THE_REQUEST} &quot;\\s(\/[^?\\s]+)\/(?=\\?|\\s)&quot;\nRewriteRule ^(.+)\/$ https:\/\/www.example.com%1 [R=301,L,NE]\n<\/code><\/pre>\n<h3><span id=\"Moving_a_whole_folder_category_change\">Moving a whole folder (category change)<\/span><\/h3>\n<p>Suppose \/blog\/ is being renamed to \/articles\/ and all posts keep the same slug.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\nRewriteCond %{THE_REQUEST} &quot;\\s\/blog\/([^?\\s]*)(?:\\?|\\s)&quot;\nRewriteRule ^blog\/ https:\/\/www.example.com\/articles\/%1 [R=301,L,NE]\n<\/code><\/pre>\n<p>The raw request-line capture includes the suffix after \/blog\/; the query is copied separately by RewriteRule. The target must serve equivalent content. Test the rule alongside host\/scheme canonicalisation, slash rules and any earlier internal rewrite; an encoded alternative to the literal \/blog\/ prefix needs its own decision.<\/p>\n<h3><span id=\"Removing_php_file_extensions\">Removing .php file extensions<\/span><\/h3>\n<p>This example hides .php for existing, top-level PHP files with ASCII letter, digit, underscore or hyphen basenames. It assumes an already configured PHP handler, MultiViews disabled and no conflicting front-controller rules. It does not try to infer every application route or nested script path.<\/p>\n<ol>\n<li>Redirect only a client request that explicitly names an existing .php file. THE_REQUEST remains the original request line during internal rewrites.<\/li>\n<li>Then internally route an extensionless path only when no file or directory already exists and the corresponding PHP file does exist. END stops later per-directory rewrite rounds.<\/li>\n<\/ol>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">Options -MultiViews\nRewriteEngine On\n\nRewriteCond %{THE_REQUEST} &quot;\\s\/+[A-Za-z0-9_-]+\\.php(?:\\?|\\s)&quot;\nRewriteCond %{REQUEST_FILENAME} -f\nRewriteRule ^([A-Za-z0-9_-]+)\\.php$ https:\/\/www.example.com\/$1 [R=301,L]\n\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_FILENAME}.php -f\nRewriteRule ^([A-Za-z0-9_-]+)$ $1.php [END]\n<\/code><\/pre>\n<p>With page.php present, \/page.php redirects to \/page, while \/page executes page.php through the existing PHP handler without redirecting back. Queries are retained. Options -MultiViews requires the corresponding server permission; have the administrator set it if .htaccess cannot. Existing static files and directories are excluded. This is not a WordPress\/Laravel front-controller configuration.<\/p>\n<h3><span id=\"Handling_query_strings_safely\">Handling query strings safely<\/span><\/h3>\n<p>For a RewriteRule target without a new query, the existing query is copied by default. QSD discards it; a replacement query normally replaces it, while QSA combines queries. The following campaign example intentionally drops every parameter once utm_campaign=old-promo matches, so confirm that no discarded parameter changes the page\u2019s required behavior.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\nRewriteCond %{QUERY_STRING} (^|&amp;)utm_campaign=old-promo(&amp;|$)\nRewriteRule ^landing\\.php$ https:\/\/www.example.com\/new-landing\/ [R=301,L,QSD]\n<\/code><\/pre>\n<p>QSD is available in Apache 2.4. This pattern matches a literal query component; encoded names, repeated parameters and application-specific interpretation need a separate rule. The target does not receive the original query.<\/p>\n<h3><span id=\"When_to_use_410_Gone_instead_of_301\">When to use 410 (Gone) instead of 301<\/span><\/h3>\n<p>When content is permanently removed and has no relevant replacement, return 404 or 410. Do not redirect it to an unrelated home page, and do not return 410 merely to exclude a still-useful page from search. This exact path example uses the same module as the other rules:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">RewriteEngine On\nRewriteRule ^old-section\/bad-content\\.html$ - [G,L]\n<\/code><\/pre>\n<p>For more on deciding between 404, 410 and 301, again see our article on <a href=\"https:\/\/www.dchost.com\/blog\/en\/what-http-status-codes-mean-for-seo-and-hosting\/\">HTTP status codes and their SEO impact<\/a>.<\/p>\n<h2><span id=\"301_Redirect_Patterns_in_Nginx\">301 Redirect Patterns in Nginx<\/span><\/h2>\n<p>On VPS, <a href=\"https:\/\/www.dchost.com\/dedicated-server\">dedicated servers<\/a> and other environments where you manage Nginx, redirects belong in server configuration rather than .htaccess. sites-available\/sites-enabled is one packaging convention; inspect the actual include paths. Configuration access depends on the service plan. Validate syntax before a controlled reload; this alone does not verify redirect behavior.<\/p>\n<h3><span id=\"Basics_return_vs_rewrite\">Basics: return vs rewrite<\/span><\/h3>\n<ul>\n<li><strong>return:<\/strong> Finishes processing with a status and target; useful for fixed destinations and variables. It does not automatically append the original query.<\/li>\n<li><strong>rewrite:<\/strong> Changes a URI using a regex. Flags determine whether it redirects or continues internal processing; changed URI and query handling must be considered.<\/li>\n<li><strong>Location selection:<\/strong> Exact matches stop the search; regex order matters. An added regex location can bypass the intended PHP handler. Prefer server-level maps\/returns or carefully scoped exact locations for these examples.<\/li>\n<\/ul>\n<h3><span id=\"HTTP_to_HTTPS_redirect_server\">HTTP to HTTPS redirect server<\/span><\/h3>\n<p>Common pattern: one server block for HTTP that only redirects, and another for HTTPS that serves content.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">server {\n    listen 80;\n    listen [::]:80;\n    server_name example.com www.example.com;\n    return 301 https:\/\/www.example.com$request_uri;\n}\n<\/code><\/pre>\n<p>This HTTP-only block combines scheme and host canonicalisation into a fixed HTTPS www target. It does not serve HTTPS or cover an existing HTTPS bare-domain entry point; the next example adds both TLS blocks. Configure default virtual hosts to reject unrelated hostnames.<\/p>\n<h3><span id=\"Nonwww_to_www_or_reverse_on_Nginx\">Non\u2011www to www (or reverse) on Nginx<\/span><\/h3>\n<p>This complete routing skeleton assumes Nginx itself terminates TLS. Install a certificate whose SAN covers both example.com and www.example.com, supply its full chain and protected key at the shown paths, and set the actual document root. A wildcard for *.example.com alone does not cover example.com. The final block serves static content only; replace its content handler with the validated application configuration when PHP or a framework is involved.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">server {\n    listen 80;\n    listen [::]:80;\n    server_name example.com www.example.com;\n    return 301 https:\/\/www.example.com$request_uri;\n}\n\nserver {\n    listen 443 ssl;\n    listen [::]:443 ssl;\n    server_name example.com;\n    ssl_certificate \/etc\/nginx\/tls\/example\/fullchain.pem;\n    ssl_certificate_key \/etc\/nginx\/tls\/example\/privkey.pem;\n    ssl_protocols TLSv1.2 TLSv1.3;\n    return 301 https:\/\/www.example.com$request_uri;\n}\n\nserver {\n    listen 443 ssl;\n    listen [::]:443 ssl;\n    server_name www.example.com;\n    ssl_certificate \/etc\/nginx\/tls\/example\/fullchain.pem;\n    ssl_certificate_key \/etc\/nginx\/tls\/example\/privkey.pem;\n    ssl_protocols TLSv1.2 TLSv1.3;\n    root \/var\/www\/example\/public;\n    location \/ {\n        try_files $uri $uri\/ =404;\n    }\n}\n<\/code><\/pre>\n<p>To choose bare-domain canonical URLs, swap the two HTTPS host roles and use https:\/\/example.com in all return targets. Both public names still need valid TLS coverage. A certificate error occurs before the HTTP redirect and cannot be repaired by it. Behind a TLS-terminating proxy, the trusted edge must own the public scheme decision.<\/p>\n<h3><span id=\"Folder_move_with_regex\">Folder move with regex<\/span><\/h3>\n<p>Use a raw-request map to move the literal \/blog\/ prefix while preserving the encoded suffix and query. Put map in the http context and the if\/return fragment inside the existing canonical server block. These are two insertion locations, not a complete standalone Nginx configuration.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\"># http context, outside server blocks\nmap $request_uri $legacy_blog_target {\n    default &quot;&quot;;\n    ~^\/blog\/(?&lt;legacy_blog_suffix&gt;.*)$ https:\/\/www.example.com\/articles\/$legacy_blog_suffix;\n}\n\n# Inside the existing canonical server block\nif ($legacy_blog_target != &quot;&quot;) {\n    return 301 $legacy_blog_target;\n}\n<\/code><\/pre>\n<p>The captured raw suffix already contains any query, so adding $is_args$args would duplicate it. The map is case-sensitive and does not match \/Blog\/ or an encoded variant of the \/blog\/ prefix. Map those intentionally if they existed. Apply final content mappings before any broader return that would introduce another hop; preserve the normal application locations for requests that do not match.<\/p>\n<h3><span id=\"Adding_or_removing_trailing_slash\">Adding or removing trailing slash<\/span><\/h3>\n<p>A generic regex location for every extensionless path can intercept PHP, static files or application routing. Instead, this example lists known virtual page routes. Use it only where \/about and \/help are not physical files\/directories and the application supports the slash targets. The map belongs in http, and the return fragment in the canonical server:<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">map $uri $page_slash_target {\n    default &quot;&quot;;\n    ~^\/about$ https:\/\/www.example.com\/about\/;\n    ~^\/help$ https:\/\/www.example.com\/help\/;\n}\n\nif ($page_slash_target != &quot;&quot;) {\n    return 301 $page_slash_target$is_args$args;\n}\n<\/code><\/pre>\n<p>For a no-slash policy, use the following alternative map and the same return fragment. Do not install both maps. Keep real directories out of this list; Nginx\u2019s static directory redirect can otherwise add the slash back.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\">map $uri $page_slash_target {\n    default &quot;&quot;;\n    ~^\/about\/$ https:\/\/www.example.com\/about;\n    ~^\/help\/$ https:\/\/www.example.com\/help;\n}\n<\/code><\/pre>\n<p>These anchored, case-sensitive mappings do not create catch-all locations, so unmatched requests continue through the existing handler selection. Queries are explicitly retained. Inventory physical directories, aliases and application-level slash behavior before choosing the mapped virtual routes; file-extension heuristics alone cannot establish that a route is safe to change.<\/p>\n<h3><span id=\"Removing_php_extension_in_Nginx\">Removing .php extension in Nginx<\/span><\/h3>\n<p>For one existing public script, use an explicit mapping from \/about to \/about.php. Insert these locations into a canonical HTTPS server whose root is \/var\/www\/example\/public. The PHP-FPM socket must already exist and be accessible to Nginx. Inspect fastcgi_params: it should supply the normal CGI parameters, including SCRIPT_NAME, without a duplicate SCRIPT_FILENAME definition.<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">location = \/about.php {\n    return 301 https:\/\/www.example.com\/about$is_args$args;\n}\n\nlocation = \/about {\n    rewrite ^ \/about.php break;\n    try_files $uri =404;\n    include \/etc\/nginx\/fastcgi_params;\n    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n    fastcgi_pass unix:\/run\/php\/php-fpm.sock;\n}\n<\/code><\/pre>\n<p>The internal rewrite uses break, so processing stays in the \/about location and reaches its FastCGI handler; it does not select the external \/about.php redirect. try_files checks for the script before FastCGI and returns 404 when absent. It must not be replaced with try_files $uri.php in a static location: finding a PHP file there does not automatically select a PHP handler. Apply explicit mappings or the framework\u2019s front controller to other routes, retain existing PHP-access restrictions, and ensure every served PHP path reaches PHP-FPM rather than static delivery. The <a href=\"https:\/\/nginx.org\/en\/docs\/http\/ngx_http_core_module.html#try_files\" rel=\"nofollow noopener\" target=\"_blank\">Nginx try_files documentation<\/a> explicitly describes processing in the current context.<\/p>\n<h3><span id=\"Redirecting_individual_pages_clean_syntax\">Redirecting individual pages (clean syntax)<\/span><\/h3>\n<p>For small sets of changed URLs where you do not need regex, keep it readable with exact locations:<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">location = \/blog\/2022\/09\/seo-tips.html {\n    return 301 https:\/\/www.example.com\/blog\/seo-tips\/$is_args$args;\n}\n\nlocation = \/shop\/product-123.html {\n    return 301 https:\/\/www.example.com\/store\/new-product-slug\/$is_args$args;\n}\n<\/code><\/pre>\n<p>location = matches the normalized path; it does not compare the query. These targets explicitly retain the query. An exact PHP location that handles only selected parameters must have a terminal error or its own configured application handler for all other cases; a general PHP regex will not take over afterward.<\/p>\n<h3><span id=\"Handling_query_strings_in_Nginx_redirects\">Handling query strings in Nginx redirects<\/span><\/h3>\n<p>$request_uri explicitly includes the original path and query. return copies only the URL you supply; a fixed target has no automatic query preservation. When changing a path, append $is_args$args if the query should remain, or deliberately omit it when the whole query should be removed.<\/p>\n<pre class=\"language-bash line-numbers\"><code class=\"language-bash\"># Original path and query are included explicitly\nreturn 301 https:\/\/www.example.com$request_uri;\n\n# Alternative: fixed path, no original query\nreturn 301 https:\/\/www.example.com\/clean-landing\/;\n<\/code><\/pre>\n<p>For an exact, retired campaign endpoint, a strict full-query match makes the discard policy explicit. This example accepts only utm_campaign=old-promo and returns 404 for every other query:<\/p>\n<pre class=\"language-nginx line-numbers\"><code class=\"language-nginx\">location = \/landing.php {\n    if ($args = &quot;utm_campaign=old-promo&quot;) {\n        return 301 https:\/\/www.example.com\/new-landing\/;\n    }\n    return 404;\n}\n<\/code><\/pre>\n<p>$arg_utm_campaign can inspect that argument but does not validate the meaning of other or repeated parameters. Here $args matches the full query; extra parameters intentionally do not match. If other requests remain valid, route them to an explicitly configured application handler instead of this terminal 404. These if blocks only return; do not extend them into an unreviewed mixture of rewrites, aliases and handlers.<\/p>\n<h2><span id=\"Testing_Monitoring_and_Cleaning_Up_After_the_Change\">Testing, Monitoring and Cleaning Up After the Change<\/span><\/h2>\n<p>Writing redirect rules is only half of the job. The rest is proving they behave as intended and updating all the surrounding SEO signals.<\/p>\n<h3><span id=\"How_to_test_your_redirects\">How to test your redirects<\/span><\/h3>\n<ul>\n<li><strong>HTTP checks:<\/strong> Inspect representative old addresses in browser developer tools, then automate the entire mapping. Verify initial status, exact Location, hop count, final 200 response and actual destination content.<\/li>\n<li><strong>GET test:<\/strong> <code>curl --silent --show-error --location --max-redirs 5 --dump-header - --output \/dev\/null https:\/\/example.com\/old-url\/<\/code> follows the chain with GET. A separate -I request uses HEAD, which can behave differently.<\/li>\n<li><strong>Cases:<\/strong> Include known and unknown query values, repeated\/encoded parameters, one-character routes, files, real directories, Unicode\/encoded path characters, HTTP\/HTTPS, both approved hostnames and an unrelated host. Check PHP execution without returning source text.<\/li>\n<li><strong>Rollout:<\/strong> Test the exact merged server\/application configuration. A syntax check cannot prove routing correctness. Browsers and CDNs can cache 301 responses, so reverting a config does not immediately undo every cached redirect.<\/li>\n<\/ul>\n<p>Fix any 302s where you meant 301, and collapse chains (A\u2192B\u2192C) into a single hop (A\u2192C) whenever you can.<\/p>\n<h3><span id=\"Update_internal_links_canonicals_and_sitemaps\">Update internal links, canonicals and sitemaps<\/span><\/h3>\n<p>Once the new structure is live, update your own links while keeping old-address redirects available:<\/p>\n<ul>\n<li>Update menus, body links, media URLs and templates to use the final addresses directly. For WordPress data, use backups, a dry run and a serialized-data-aware tool; avoid blind SQL replacements and unnecessary GUID changes.<\/li>\n<li>Ensure each new canonical page references itself, and update hreflang alternates where applicable.<\/li>\n<li>Submit a sitemap containing the new canonical URLs. The <a href=\"https:\/\/www.dchost.com\/blog\/en\/setting-up-robots-txt-and-sitemap-xml\/\">robots.txt and sitemap guide<\/a> explains the setup. Remove staging noindex blocks from indexable targets and let crawlers access old redirects.<\/li>\n<\/ul>\n<p>If you are also consolidating multiple domains (for example redirecting regional domains into one main site), coordinate your redirect rules with canonical tags and Hreflang. Our article on <a href=\"https:\/\/www.dchost.com\/blog\/en\/pointing-multiple-domains-to-one-website\/\">pointing multiple domains to one website with 301 redirects and canonical tags<\/a> dives into those patterns.<\/p>\n<h3><span id=\"Watch_logs_and_Search_Console\">Watch logs and Search Console<\/span><\/h3>\n<p>After deployment, your server logs are your best friend:<\/p>\n<ul>\n<li>Filter for <strong>404 responses<\/strong> and see which paths are still being requested. Decide whether each should get a 301 to an equivalent page or remain a 404\/410.<\/li>\n<li>Monitor <strong>5xx errors<\/strong> (500, 502, 504) that might indicate misconfiguration or loops.<\/li>\n<\/ul>\n<p>Use Page indexing reports and URL Inspection to compare representative old and new URLs. A redirected old URL being excluded from the index is expected; unexpected 404s, soft 404s, blocked targets or incorrect canonicals require investigation. Google processes a move per URL, so there is no fixed recovery deadline. Visibility may fluctuate; larger sites can take longer than the few weeks typical of processing many small-site moves. See <a href=\"https:\/\/developers.google.com\/search\/docs\/crawling-indexing\/site-move-with-url-changes\" rel=\"nofollow noopener\" target=\"_blank\">Google\u2019s site-move guidance<\/a> for processing time, redirect retention and migration signals.<\/p>\n<h3><span id=\"Special_case_changing_domain_names\">Special case: changing domain names<\/span><\/h3>\n<p>If you are not just reshaping paths, but moving from one domain to another, the redirect rules are similar but the stakes are higher. You will want:<\/p>\n<ul>\n<li>Map each moved old-domain URL directly to its final equivalent on the new domain, including any path change. Do not deliberately introduce a domain-hop then a path-hop.<\/li>\n<li>Maintain old-domain DNS and valid TLS for the redirect lifetime; prepare the new domain\u2019s DNS, <a href=\"https:\/\/www.dchost.com\/ssl\">TLS certificates<\/a> and dependent services. Email changes are a separate migration with their own MX\/authentication\/routing requirements.<\/li>\n<li>Use Search Console\u2019s Change of Address for an eligible domain\/subdomain move; it is not needed for a path-only, HTTP-to-HTTPS or same-domain www\/non-www change.<\/li>\n<\/ul>\n<p>We have a dedicated walkthrough on <a href=\"https:\/\/www.dchost.com\/blog\/en\/how-to-change-your-domain-without-losing-seo\/\">how to change your domain without losing SEO<\/a>, including hosting\u2011side and DNS considerations.<\/p>\n<h2><span id=\"Wrapping_Up_Practical_Checklist_and_Next_Steps\">Wrapping Up: Practical Checklist and Next Steps<\/span><\/h2>\n<p>A URL migration succeeds technically when old addresses reach appropriate final content and the application, links and indexing signals agree. Clear mapping, tested redirects and monitoring reduce the risk of lost traffic; they cannot promise unchanged rankings. Removed content without a relevant replacement should return 404\/410.<\/p>\n<p>On shared hosting, confirm which .htaccess directives are allowed. On managed or self-managed VPS, dedicated and colocation services, clarify who owns configuration and deployment. Keep redirects for as long as possible, generally at least a year according to Google, and longer where old external links remain useful. Measure configuration cost rather than assuming thousands of rules are free. The <a href=\"https:\/\/www.dchost.com\/blog\/en\/website-launch-checklist-hosting-seo-and-performance\/\">website launch checklist<\/a> helps coordinate the application and hosting work.<\/p>\n<p>When choosing DCHost infrastructure, verify the selected plan\u2019s configuration access and management scope. A concrete URL inventory, deployment plan and post-launch checks make the required work clear without assuming that every hosting service includes application-level migration.<\/p>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Map old URLs to final destinations and verify Apache and Nginx redirects, query behavior, PHP routing, HTTPS aliases and the surrounding indexing signals.<\/p>\n","protected":false},"author":1,"featured_media":13312,"comment_status":"","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[184],"tags":[],"class_list":["post-3908","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3908","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/comments?post=3908"}],"version-history":[{"count":5,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3908\/revisions"}],"predecessor-version":[{"id":13314,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/posts\/3908\/revisions\/13314"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media\/13312"}],"wp:attachment":[{"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/media?parent=3908"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/categories?post=3908"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.dchost.com\/blog\/en\/wp-json\/wp\/v2\/tags?post=3908"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}